Mastering Rust
上QQ阅读APP看书,第一时间看更新

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.