admin管理员组文章数量:1399839
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.
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.
- 2 Ever hear that you should program to interfaces rather than concrete implementations? Also, traits can have default implementations. You use a trait when you want to decouple a behavior (verb) from a specific struct (noun). Glancing at your profile it looks like you're a Python programmer. This idea is not as big a deal in dynamically typed languages: there you'd probably use some sort of mixin pattern instead. – Jared Smith Commented Mar 25 at 13:03
1 Answer
Reset to default 3Polymorphism
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.
本文标签:
版权声明:本文标题:Why use Rust traits for "implementing shared behavior" if each object with the same trait still needs its own 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744194755a2594685.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论