- Mastering Rust
- Rahul Sharma Vesa Kaihlavirta
- 122字
- 2021-07-02 13:35:29
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.
推薦閱讀
- Spring 5.0 By Example
- Learning RabbitMQ
- 神經網絡編程實戰:Java語言實現(原書第2版)
- Web Development with Django Cookbook
- Bootstrap Essentials
- Scala程序員面試算法寶典
- Python機器學習:預測分析核心算法
- Couchbase Essentials
- Advanced UFT 12 for Test Engineers Cookbook
- Photoshop智能手機APP界面設計
- Software Development on the SAP HANA Platform
- 實戰Python網絡爬蟲
- Spring Data JPA從入門到精通
- JavaEE架構與程序設計
- Puppet 5 Beginner's Guide(Third Edition)