4 ms·
That's the way round I meant. Yes you can have generics without traits (particularly with data structures as you've pointed out). Not sure of anything that uses
by rkangel 9y ago
That's the way round I meant. Yes you can have generics without traits (particularly with data structures as you've pointed out). Not sure of anything that uses traits without generics.
- kibwen 9y ago> Not sure of anything that uses traits without generics. Traits do a lot of things in Rust that have nothing to do with generics. :) Implementing a trait is how one gives a type a destructor. Implementing various traits (the ones in std::ops) allows one to do operator overloading for user-defined types. Defining a trait allows one to give methods to types that are defined in other compilation units, including the standard library, e.g.: trait Foo { fn foo(self); } impl Foo for i32 { fn foo(self) { println!("Hello, traits!"); } } fn main() { 42.foo(); // Hello, traits! }
- rkangel 9y agoThank you for that.
- saghm 9y agoHow about Read and Write, two of the most widely-used traits? https://doc.rust-lang.org/std/io/trait.Read.html https://doc.rust-lang.org/std/io/trait.Read.html https://doc.rust-lang.org/std/io/trait.Write.html https://doc.rust-lang.org/std/io/trait.Write.html
- rkangel 9y agoBut those are excellent examples of the use of generics. They allow you write code that can operates on a generic object, not know what type it is, but know that you can read from it.
- saghm 9y agoOh, I think I see what you're saying. If I'm understanding correctly, then you're saying that the types that traits define are only used with generics? This isn't quite correct, as you can use trait objects to get dynamic dispatch rather than using generics. But yes, in general, functions that are defined to take traits as parameters generally use generics. I'm not sure I'd still consider the idea of traits to be inherently tied to generics, though; the Iterator trait, for instance, is usually just used to call Iterator methods on different types rather than as a way to bound the types of function parameters.