特征(Trait)

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

  1. trait Pet {
  2. /// Return a sentence from this pet.
  3. fn talk(&self) -> String;
  4. /// Print a string to the terminal greeting this pet.
  5. fn greet(&self);
  6. }

This slide and its sub-slides should take about 15 minutes.

  • trait 定义了类型实现该 trait 所必须具备的一些方法。

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