- Hands-On Data Structures and Algorithms with Rust
- Claus Matzinger
- 273字
- 2021-07-02 14:11:41
Objects and behavior
Organizing code in Rust is a bit different from regular object-oriented languages such as C#. There, an object is supposed to change its own state, interfaces are simple contract definitions, and specialization is often modeled using class inheritance:
class Door {
private bool is_open = false;
public void Open() {
this.is_open = true;
}
}
With Rust, this pattern would require constant mutability of any Door instance (thereby requiring explicit locking for thread safety), and without inheritance GlassDoor would have to duplicate code, making it harder to maintain.
Instead, it's recommended to create traits to implement (shared) behavior. Traits have a lot in common with abstract classes in traditional languages (such as default implementations of methods/functions), yet any struct in Rust can (and should) implement several of those traits:
struct Door {
is_open: bool
}
impl Door {
fn new(is_open: bool) -> Door {
Door { is_open: is_open }
}
}
trait Openable {
fn open(&mut self);
}
impl Openable for Door {
fn open(&mut self) {
self.is_open = true;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn open_door() {
let mut door = Door::new(false);
door.open();
assert!(door.is_open);
}
}
This pattern is very common in the standard library, and often third-party libraries will even add behavior to existing types by implementing traits in their code (also known as extension traits).
Other than a typical class, where data fields and methods are in a single construct, Rust emphasizes the separation between those by declaring a struct for data and an impl part for the methods/functions. Traits name and encapsulate behaviors so they can easily be imported, shared, and reused.
- Python數據分析入門:從數據獲取到可視化
- Oracle RAC 11g實戰指南
- 云計算服務保障體系
- PySpark大數據分析與應用
- Enterprise Integration with WSO2 ESB
- iOS and OS X Network Programming Cookbook
- Remote Usability Testing
- OracleDBA實戰攻略:運維管理、診斷優化、高可用與最佳實踐
- 數據庫設計與應用(SQL Server 2014)(第二版)
- AI時代的數據價值創造:從數據底座到大模型應用落地
- 重復數據刪除技術:面向大數據管理的縮減技術
- 一本書講透Elasticsearch:原理、進階與工程實踐
- 計算機視覺
- 利用Python進行數據分析(原書第2版)
- Cognitive Computing with IBM Watson