官术网_书友最值得收藏!

  • Mastering Rust
  • Rahul Sharma Vesa Kaihlavirta
  • 247字
  • 2021-07-02 13:35:30

Abstracting behavior with traits

From a polymorphism and code reuse perspective, it is often a good idea to separate shared behavior and common properties of types from themselves in code and only have methods that are unique to themselves. In doing so, we allow different types to relate to each other with these common properties, which allows us to program for APIs that are more general or inclusive in terms of their parameters. This means that we can accept types that have those shared properties while not being restricted to one particular type.

In object-oriented languages such as Java or C#, interfaces convey the same idea, where we can define shared behavior that many types can implement. For example, instead of having multiple sort functions, which take in a list of integer values, and other functions that take in a list of string values, we can have a single sort function that can take a list of items that implement the Comparable or Comparator interface. This allows us to pass anything that is Comparable to our sort function.

Rust also has a similar yet powerful construct known as traits. There are many forms of traits in Rust, and we'll look at most of them and the ways we can interact with them briefly. Also, when traits are mixed with generics, we can restrict the range of parameters that we can pass to our APIs. We'll see how that happens when we learn more about trait bounds.

主站蜘蛛池模板: 壤塘县| 汉寿县| 霍山县| 长武县| 娄底市| 铁岭县| 郎溪县| 盐边县| 赤峰市| 海丰县| 大化| 邮箱| 兴安盟| 咸丰县| 师宗县| 富蕴县| 望都县| 平乡县| 乐陵市| 晴隆县| 安西县| 乌鲁木齐市| 类乌齐县| 安平县| 哈尔滨市| 嘉鱼县| 平阳县| 东宁县| 泰来县| 克东县| 孟村| 潞西市| 阆中市| 临沂市| 吴桥县| 竹溪县| 山阴县| 尼玛县| 峨眉山市| 湟中县| 新沂市|