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

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.

主站蜘蛛池模板: 石台县| 宜良县| 涪陵区| 常山县| 思茅市| 安阳市| 高尔夫| 保康县| 工布江达县| 电白县| 阜新| 交口县| 涿州市| 太和县| 金溪县| 余江县| 东乌珠穆沁旗| 犍为县| 原阳县| 乌兰察布市| 平顺县| 板桥市| 西畴县| 武冈市| 邳州市| 渝中区| 平顶山市| 罗平县| 溧水县| 江孜县| 玉田县| 凤台县| 个旧市| 莎车县| 修水县| 中牟县| 宿州市| 通榆县| 都昌县| 南京市| 安泽县|