特征(Trait)

Rust 让您可以依据特征对类型进行抽象化处理。特征与接口类似:

trait Pet {
    /// Return a sentence from this pet.
    fn talk(&self) -> String;

    /// Print a string to the terminal greeting this pet.
    fn greet(&self);
}
  • trait 定义了类型实现该 trait 所必须具备的一些方法。

  • In the “Generics” segment, next, we will see how to build functionality that is generic over all types implementing a trait.