- Hands-On Data Structures and Algorithms with Rust
- Claus Matzinger
- 254字
- 2021-07-02 14:11:49
Generics
Rust supports generics and even allows us to enforce the implementation of certain traits. These constraints can either come as a where clause attached to the function definition or with a colon in the generic type declaration:
fn my_generic_func<T: MyTrait>(t: T) {
// code
}
// ... is the same as
fn my_generic_func <T>(t: T) where T: MyTrait {
// code
}
// but better use in 2018 and beyond
fn my_generic_func(t: impl MyTrait) {
// code
}
Additionally, the 2018 impl Trait syntax simplifies single-trait requirements (to do static instead of dynamic dispatch) for input and return parameters, thereby eliminating the need for a Box or lengthy type constraints (such as MyTrait in the preceding snippet). Unless multiple trait implementations are required (for example, fn f(x: T) where T: Clone + Debug + MyTrait {}), the impl Trait syntax allows us to put them where they matter, which is into the parameter list:
fn my_generic_func<T>(t: T) {
// code
}
// ... is the same as
fn my_generic_func <T: Sized>(t: T) {
// code
}
When working with generics, the situation is a bit more complex. Type parameters are Sized by default (see the preceding snippet), which means that they will not match unsized types. To match those as well, the special ?Sized type constraint can be used. This snippet also shows the required change to passing in a reference:
fn my_generic_func <T: ?Sized>(t: &T) {
// code
}
However, any type of heap-allocated reference will incur an extra step to access the contained value.
- 公有云容器化指南:騰訊云TKE實戰(zhàn)與應(yīng)用
- PyTorch深度學習實戰(zhàn):從新手小白到數(shù)據(jù)科學家
- 數(shù)據(jù)庫原理及應(yīng)用教程(第4版)(微課版)
- Word 2010中文版完全自學手冊
- 從零開始學Hadoop大數(shù)據(jù)分析(視頻教學版)
- 數(shù)據(jù)庫基礎(chǔ)與應(yīng)用:Access 2010
- Voice Application Development for Android
- Live Longer with AI
- 數(shù)據(jù)驅(qū)動設(shè)計:A/B測試提升用戶體驗
- Spark大數(shù)據(jù)分析實戰(zhàn)
- 大數(shù)據(jù)技術(shù)入門
- Python數(shù)據(jù)分析與挖掘?qū)崙?zhàn)(第3版)
- 數(shù)據(jù)科學實戰(zhàn)指南
- 貫通SQL Server 2008數(shù)據(jù)庫系統(tǒng)開發(fā)
- 從Lucene到Elasticsearch:全文檢索實戰(zhàn)