by webkike · 11y ago · 0 comments
Traits are types, though you need to put them behind a pointer (Box<Trait> or &Trait) if you want to use them as types; and this is dynamic dispatch.
You can use them in static dispatch (generics) too, and in general you should try to do that whenever possible. Plus there are loads of things you can do with them that Go can't (static trait methods, associated items, generics, etc)
The only feature that Go interfaces have that Rust traits don't is auto-implementation, and that's a misfeature IMO. It works okay for Go, but in Rust it makes more sense to explicitly say that you are implementing a trait.
type ExInterface interface { ... }
type ExStruct {
arr []ExInterface
}
Each element of arr need not be the same type, so long as it implements ExInterface. In Rust, the only thing I can do that is similar is: struct<t: ExTrait> ExStruct {
arr: Vec<t>,
}
Which means that each element of arr not only has to implement ExTrait, but also has to be of consistent type with the rest of the elements. If I want the same level of flexibility the Go gives me, I need to make an enum of each possible type that arr can contain. type StructOne struct {
field uint32
}
type StructTwo struct {
field uint64
}
It's pretty clear that these structures are of different size. Now, if both of these structures implement the "Foo" interface, we can't simply make an array like []Foo, since we'd have no practical method to index into the array. Go solves this by making []Foo actually be an array of pointers.However, Rust's philosophy is, AFAIK, "be explicit about the cost you pay". So, if you want to make an "array of things that implement Foo", you need to explicitly put the "things" behind a pointer, or a Box<>. So, you get:
struct MyStruct {
arr: Vec<Box<Foo>>,
}
Which makes it explicit that you're storing a "list of pointers to things that implement Foo". Of course, the nice part is that you can use generic syntax to make an array that doesn't use pointers, like so: struct MyStruct2<T: Foo> {
arr: Vec<T>,
}
In the above, you can only store items of a single type in the `arr` field, and the generics constrain that to be only types `T` that implement Foo. The upside is, however, that you don't have any pointer indirection (and the compiler monomorphizes - i.e. generates new code for each generic implementation), so your code is probably faster / easier for LLVM to optimize.