[英]How can I use enum variants as generic type?
我想使用枚舉作為泛型結構的類型變體。
這給了我一個錯誤:
#[derive(Debug)]
enum Role {
User,
Admin,
}
#[derive(Debug)]
struct Session<T> {
id: i64,
role: T,
}
fn only_for_user(s: Session<Role::User>) {
println!("{:?}", s);
}
fn only_for_admin(s: Session<Role::Admin>) {
println!("{:?}", s);
}
fn main() {
let session = Session {
id: 1,
role: Role::User,
};
only_for_user(session);
}
error[E0573]: expected type, found variant `Role::User`
--> src/main.rs:13:29
|
13 | fn only_for_user(s: Session<Role::User>) {
| ^^^^^^^^^^
| |
| not a type
| help: try using the variant's enum: `crate::Role`
error[E0573]: expected type, found variant `Role::Admin`
--> src/main.rs:17:30
|
17 | fn only_for_admin(s: Session<Role::Admin>) {
| ^^^^^^^^^^^
| |
| not a type
| help: try using the variant's enum: `crate::Role`
游樂場。
你不能這樣做。 枚舉變體本身不是類型(有一個 RFC ,但是它被推遲了)。
做這種事情的通常方法是擁有一個包含變體數據的結構並使變體包含這個結構:
#[derive(Debug)]
struct User;
#[derive(Debug)]
struct Admin;
#[derive(Debug)]
enum Role {
User(User),
Admin(Admin),
}
#[derive(Debug)]
struct Session<T> {
id: i64,
role: T,
}
fn only_for_user(s: Session<User>) {
println!("{:?}", s);
}
fn only_for_admin(s: Session<Admin>) {
println!("{:?}", s);
}
fn main() {
let session = Session {
id: 1,
role: User,
};
only_for_user(session);
}
您可以將枚舉和結構與特征聯系在一起。
你可以用特質來做到這一點。
trait Role: std::fmt::Debug {}
#[derive(Debug)]
struct User;
impl Role for User {}
#[derive(Debug)]
struct Admin;
impl Role for Admin {}
#[derive(Debug)]
struct Session<T: Role> {
id: i64,
role: T,
}
fn only_for_user(s: Session<User>) {
println!("{:?}", s);
}
fn only_for_admin(s: Session<Admin>) {
println!("{:?}", s);
}
fn main() {
let session = Session {
id: 1,
role: User {},
};
only_for_user(session);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.