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

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.

主站蜘蛛池模板: 富锦市| 宝应县| 科技| 金坛市| 巴马| 孟州市| 星座| 卢氏县| 德保县| 凤翔县| 五大连池市| 高邑县| 鹤峰县| 兴文县| 平安县| 乐亭县| 江安县| 大理市| 阿瓦提县| 库尔勒市| 高台县| 永昌县| 阳江市| 永嘉县| 南汇区| 元氏县| 聂拉木县| 汕头市| 平远县| 郎溪县| 马公市| 山西省| 油尖旺区| 都江堰市| 嫩江县| 浦北县| 静乐县| 嘉鱼县| 泊头市| 梓潼县| 香河县|