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

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.

主站蜘蛛池模板: 阳信县| 三穗县| 资中县| 苏州市| 金沙县| 桃源县| 鄂托克前旗| 宜州市| 乐昌市| 同江市| 广平县| 基隆市| 南江县| 山阴县| 纳雍县| 中牟县| 云梦县| 仁怀市| 灌南县| 铜山县| 诏安县| 安康市| 竹山县| 电白县| 剑阁县| 潞西市| 娄烦县| 栾川县| 朝阳县| 凌海市| 龙山县| 青川县| 宁蒗| 兴文县| 诸城市| 永修县| 赤峰市| 汝州市| 青岛市| 天气| 通许县|