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

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.

主站蜘蛛池模板: 吉木乃县| 屯留县| 乌恰县| 大荔县| 嵊泗县| 白水县| 阜新| 通山县| 颍上县| 洪湖市| 安徽省| 高淳县| 志丹县| 神池县| 丘北县| 赣榆县| 原阳县| 九龙坡区| 新绛县| 灵台县| 博客| 抚州市| 岚皋县| 宣汉县| 红安县| 延庆县| 包头市| 新丰县| 溆浦县| 卫辉市| 绥芬河市| 团风县| 株洲县| 武安市| 丹阳市| 嵩明县| 永仁县| 开化县| 会昌县| 墨江| 响水县|