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.

Share Improve this question asked Mar 25 at 12:56 HeikoHeiko 752 silver badges10 bronze badges 1
  • 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
Add a comment  | 

1 Answer 1

Reset to default 3

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.

本文标签: