- 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.
- 大話PLC(輕松動(dòng)漫版)
- UI設(shè)計(jì)基礎(chǔ)培訓(xùn)教程
- Mastering OpenLayers 3
- Docker進(jìn)階與實(shí)戰(zhàn)
- Azure IoT Development Cookbook
- Manga Studio Ex 5 Cookbook
- Learning Apache Cassandra
- Building Wireless Sensor Networks Using Arduino
- Android群英傳
- Developing SSRS Reports for Dynamics AX
- Python計(jì)算機(jī)視覺和自然語言處理
- Python Machine Learning Blueprints:Intuitive data projects you can relate to
- 數(shù)據(jù)科學(xué)中的實(shí)用統(tǒng)計(jì)學(xué)(第2版)
- Monitoring Docker
- Beginning C# 7 Hands-On:The Core Language