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

Generic types

Generic structs: We can declare tuple structs and normal structs generically like so:

// generic_struct.rs

struct GenericStruct<T>(T);

struct Container<T> {
item: T
}

fn main() {
// stuff
}

Generic structs contain the generic type parameter after the name of the struct, as shown in the preceding code. With this, whenever we denote this struct anywhere in our code, we also need to type the <T> part together with the type.

Generic enums: Similarly, we can create generic enums as well:

// generic_enum.rs

enum Transmission<T> {
Signal(T),
NoSignal
}

fn main() {
// stuff
}

Our Transmission enum has a variant called Signal, which holds a generic value, and a variant called NoSignal, which is a no value variant.

主站蜘蛛池模板: 临洮县| 托克托县| 霍山县| 石棉县| 新昌县| 屏东市| 许昌市| 望都县| 高邮市| 普兰县| 武汉市| 驻马店市| 米脂县| 宜昌市| 宣汉县| 社会| 武义县| 洛宁县| 道真| 利辛县| 分宜县| 邵武市| 香港| 乾安县| 屏边| 邢台县| 建宁县| 金门县| 黄山市| 英德市| 富宁县| 收藏| 永寿县| 呼图壁县| 平陆县| 崇左市| 綦江县| 海口市| 延吉市| 河津市| 招远市|