Reading the Rust book and struggling to understand why I should use traits over methods if I still need to write an implementation of the trait for each object that can have that trait.
Apart from the convenience of being able to have the same generic names for functions in a trait for multiple objects (e.g. structs A, B and C can all have the same trait implementation name .save()
), I still have to write as much if not more code for all implementations over just writing a method for each struct.
Polymorphism
Rust's trait
is somewhat equivalent's to Go or Java's interface
: it describes an interface, separately from any implementation.
From there, you can write functions which operate on the interface regardless of the type which actually implements the trait. For example:
fn sum<I>(sequence: I) -> i64
where
I: IntoIterator<Item = i64>
{
let mut result = 0;
for i in sequence {
result += i;
}
result
}
Therefore, the shared behavior isn't in the trait, it's in the users of the trait: the behavior implemented in the structs and functions which operate on the trait (via generics or dyn
traits), regardless of the actual implementor.