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

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.

主站蜘蛛池模板: 安阳县| 白山市| 崇信县| 玛纳斯县| 衡水市| 乐都县| 永宁县| 富源县| 阿拉尔市| 且末县| 子洲县| 仪陇县| 安仁县| 禹州市| 随州市| 定陶县| 怀宁县| 东乌| 毕节市| 治县。| 武冈市| 南投市| 青神县| 元氏县| 宜宾市| 中卫市| 繁峙县| 民权县| 沧源| 济南市| 醴陵市| 宣恩县| 登封市| 吉安市| 三穗县| 启东市| 高密市| 宝丰县| 德安县| 古交市| 鸡泽县|