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

Generics

Generics are a way to make a function or a type work for multiple types to avoid code duplication. Let's rewrite our max function to make it generic:

fn max<T: PartialOrd>(a: T, b: T) -> T {
    if a > b {
        a
    } else {
        b
    }
}

The first thing to note is that there's a new part after the function name: this is where we declare the generic types. We declare a generic T type, : PartialOrd after it means that this T type must implement the PartialOrd trait. This is called a trait bound. We then use this T type for both of our parameters and the return type. Then, we see the same function body as the one from our non-generic function. We needed to add the trait bound because, by default, no operation is allowed on a generic type. The PartialOrd trait allows us to use the comparison operators.

We can then use this function with any type that implements PartialOrd:

println!("{}", max('a', 'z'));

This is using static dispatch as opposed to dynamic dispatch, meaning that the compiler will generate a max function specific to char in the resulting binary. Dynamic dispatch is another approach that resolves the right function to call at runtime, which is less efficient.

主站蜘蛛池模板: 马鞍山市| 洞口县| 祁东县| 连江县| 锡林郭勒盟| 玉溪市| 内丘县| 城市| 文成县| 呼和浩特市| 沛县| 铁力市| 专栏| 托克逊县| 大竹县| 襄城县| 无为县| 河西区| 镇坪县| 荣成市| 海南省| 连城县| 澄江县| 深水埗区| 夹江县| 宾川县| 视频| 方正县| 兴业县| 通渭县| 临澧县| 太原市| 会昌县| 万宁市| 荔波县| 长葛市| 项城市| 祁门县| 象州县| 凤山县| 南康市|