FAQ Database Discussion Community


Why is `Sized` bound necessary in this trait?

rust,traits
I have a simple trait with two associated functions like this: trait WithConstructor : Sized { fn new_with_param(param: usize) -> Self; fn new() -> Self { Self::new_with_param(0) } } The default implementation of the second method (new()) force me to put the Sized bound on the type. Why ? (I...

Best way to use a class inside another class

php,class,oop,dependency-injection,traits
I've created this class that fetches all data of a post from database. class Post { private $id; protected $conn; public $data; function __construct(\mysqli $conn) { $this->conn = $conn; } public function getId() { return $this->id; } public function getConnection() { return $this->conn; } public function getPost() { $query1 =...

Error when writing a recursive trait method with an associated type as an argument

generics,recursion,rust,traits,associated-types
I've been updating a library to use Rust's new associated types. The library offers a Node trait for constructing a DSP graph. Below is a simplified version of the trait that produces the same error I'm running into in my library. use std::default::Default; use std::num::Float; trait Node { type Output:...

When should I not implement a trait for references to implementors of that trait?

rust,traits
If I have a trait, and a function that accepts a generic type constrained to that type, everything works fine. If I try to pass in a reference to that type, I get a compilation error. trait Trait { fn hello(&self) -> u32; } struct Struct(u32); impl Trait for Struct...

Is it possible to access struct fields from within a trait?

oop,rust,traits
I know object oriented programming from C# and I'm playing around with Rust right now, obviously trying to adapt the OOP-functionalities I already know from C#. There is one thing I'm really wondering about: Traits are used to group some functions to be implemented from a struct. How is it...

Kotlin: Superclass is not accessible from trait

traits,kotlin
In Kotlin, given some class: public open class A { open fun sayHi() = "hi" } And a trait T that requires subclasses to extend A : public trait T : A { override fun sayHi() = super.sayHi() + " John" } One would expect T.sayHi to be able to...

Implement Debug trait for large array type

rust,traits
I gather that Rust provides Debug impl's for arrays size 32 and smaller. I also gather that I could implement Debug on a larger array by simply using write! with a very long format specifier. But I'm wondering if there's a better way. What is the recommended method for implementing...

using a method trait in a traitsui factory

enthought,traits,traitsui
I am trying to figure out how Method traits work and if I can use one in a factory defined in a traits View object in order to have dynamic values passed to the factory. Here is what I mean, a minimal test case which works except for the factory...

Misleading error passing OsString to a func, where does Display trait comes from?

compiler-errors,rust,traits
Why does this function call: use std::string::ToString; use std::ffi::OsString; fn len<T: ToString>(v: &T) -> usize { v.to_string().len() } fn main() { let text = OsString::from("Hello, world!"); let tlen = len(&text); println!("len('{:?}') = {}", &text, tlen); } raise this compilation error: <anon>:10:16: 10:19 error: the trait `core::fmt::Display` is not implemented for...

Nested trait types, bounded types and verbosity in use of the as keyword

rust,traits
I have question regarding the use the readability and verbosity of the as keyword for nested types within traits. I'm coming from a C++ background and I suspect that my misunderstanding will come from a lack of knowledge of the type systems used Haskell, which I understand rust makes use...

Implement fmt::Display for Vec

printf,rust,traits
I want to implement the fmt::Display for a nested struct commonly used in my code. // The root structure pub struct WhisperFile<'a> { pub path: &'a str, pub handle: RefCell<File>, pub header: Header } pub struct Header{ pub metadata: metadata::Metadata, pub archive_infos: Vec<archive_info::ArchiveInfo> } pub struct Metadata { // SNIP...

Call parent magic method from override magic method in a trait

php,traits
Problem I am open sourcing a trait which includes the magic method __call(). During testing, I encountered a challenge when the parent class of the class using the trait contains the __call method. What I Tried trait SomeTrait { public function __call($method, array $parameters) { // ... return parent::__call($method, $parameters);...

What does it mean for a trait to have a lifetime parameter?

rust,traits,lifetime
I understand how lifetime parameters apply to functions and structs, but what does it mean for a trait to have a lifetime parameter? Is it a shortcut to introduce a lifetime parameter to its methods, or is it something else?

PHP Reflection: How to know if a method/property/constant is inherited from trait?

php,inheritance,reflection,traits,trait
I want to exclude all inherited methods from trait(s) from the list that are not overriden in a class So how to know if a class member is inherited from trait? Yes, I can check it like this: if ($trait->hasMethod($methodName) || $ref->getTraitAliases()[$methodName] !== null) { // } But what if...

How do I make my own adapter methods able to consume a trait object?

rust,traits
I have a trait that has "adapter methods" that consume the method: struct Bar<T>(T); trait Foo { fn make_bar(self) -> Bar<Self> where Self: Sized { Bar(self) } } impl Foo for u8 {} impl Foo for bool {} This is modeled after Iterator. When I use a Box<Iterator>, I can...

How to restrict values in a Float trait in Enthought traits module?

python,validation,enthought,traits
I'm a bit new to Enthought traits module. I would like to specify a trait for which only a few floating-point values are allowed. Unfortunately, I can't use a Enum because it breaks the code base I'm working on. How can I specify which values are valid for a Float?...

Source trait is inaccessible

rust,visibility,traits
The situation is (severely simplified) this (playpen): mod tokentree { pub struct TokenTree; mod serialize { use std::collections::BTreeMap; use super::TokenTree; #[derive(Debug)] pub struct InternStr; pub trait InternStrsExt { fn intern_strs(&self) -> BTreeMap<&str, InternStr>; } impl InternStrsExt for [TokenTree] { fn intern_strs(&self) -> BTreeMap<&str, InternStr> { BTreeMap::new() } } } pub...

Traits with parameterized associated types

rust,traits
I come from a C++ background and was wondering if I could code up a trait for use in the foo and bar functions. #![feature(alloc)] use std::rc::{Rc, Weak}; pub trait MyTrait { /// Value type type VAL; /// Strongly boxed type /// Will be constrained to something like Box, Rc,...

Generic design mixed with curiously recurring template pattern. C++

c++,oop,templates,design-patterns,traits
Consider this kind of problem. I have a Base class and three classes derived from Base. For instance: DerivedA, DerivedB and DerivedC. Each derived class has its unique container. Hence DerivedA has std::vector<int>, DerivedB has std::set<int> and DerivedC has std::map<int, std::string>. And I want an interface in Base to access...

Keeping DRY in rust match expressions

polymorphism,rust,traits
As a simplified, self-contained example, let's say I'm parsing an input file full of shape definitions: // shapes.txt Circle: radius 1, color blue Square: edge 5, color red Triangle: edge 2 , color black Triangle: edge 2 , color white I want to parse these into structs like: struct Circle...

Retrofit with Kotlin traits that include implemented methods

java,retrofit,traits,kotlin
Traits work well with Retrofit as long as there is no extra method implemented. Depending on return type RetrofitError: TwitchApi.someMethod: HTTP method annotation is required (e.g., @GET, @POST, etc.). or java.lang.IllegalArgumentException: TwitchApi.someMethod: Must have either a return type or Callback as last argument. is thrown. Is there a way to...

How to clone a struct storing a trait object?

struct,clone,rust,traits,cloneable
I wrote a program that has trait Animal and struct Dog implementing the trait and struct AnimalHouse storing an animal as trait object Box<Animal>. trait Animal{ fn speak(&self); } struct Dog{ name: String } impl Dog{ fn new(name: &str) -> Dog { return Dog{name: name.to_string()} } } impl Animal for...

How to build WriteBuf from array

buffer,rust,traits
I am serializing two values in to an array and I am trying to go through a WriteBuf but I am getting the error that error: the trait `std::io::Write` is not implemented for the type `[_; 12]` error: type `std::io::buffered::BufWriter<&mut [_; 12]>` does not implement any method in scope named...

Trait not implemented for (thing that implements trait)

rust,traits
So, Rust is trying to tell me a fib, I think, but maybe I'm just out of my mind... fn get_random<T, R>(range: Range<T>, rng: &mut R) -> T where T: SampleRange + PartialOrd, R: Rng { range.ind_sample(&mut rng) } The where clause there should indicate that R definitely implements Rng,...

Implementing a “cautious” take_while using Peekable

iterator,rust,traits,borrow-checker
I'd like to use Peekable as the basis for a new cautious_take_while operation that acts like take_while from IteratorExt but without consuming the first failed item. (There's a side question of whether this is a good idea, and whether there are better ways to accomplish this goal in Rust --...

Using traits as types in enums

enums,polymorphism,rust,traits
Here's my code: trait UnaryOperator { fn apply(&self, expr: Expression) -> Expression; } pub enum Expression { UnaryOp(UnaryOperator, Expression), Value(i64) } Which gives the following errors: error: the trait 'core::marker::sized' is not implemented for type 'parser::UnaryOperator' note: 'parser::UnaryOperator' does not have a constant size known at compile-time I'm not sure...

Scala - Initiating a trait?

scala,traits
There is this code: // Initial object algebra interface for expressions: integers and addition trait ExpAlg[E] { def lit(x : Int) : E def add(e1 : E, e2 : E) : E } // An object algebra implementing that interface (evaluation) // The evaluation interface trait Eval { def eval()...

The trait `A` is not implemented for the type `A`

rust,traits
I am trying to use a trait that has a function that takes a closure as argument, and then use it on a trait object. trait A { fn f<P>(&self, p: P) where P: Fn() -> (); } struct B { a: Box<A> } impl B { fn c(&self) {...

Enthought Traits.HasTraits class as a nested dictionary?

python,dictionary,enthought,traits,traitsui
Imagine I have the following Traits objects: from traits.api import Int, HasTraits, Instance class Foo(HasTraits): a = Int(2) b = Int(5) class Bar(HasTraits): c = Int(7) foo = Instance(Foo,()) Bar will let me access attribute a on Foo via: bar = Bar() bar.foo.a >>> 2 Is there a standard way...