gpt4 book ai didi

rust - 如何将枚举变体用作通用类型?

转载 作者:行者123 更新时间:2023-12-05 09:01:57 24 4
gpt4 key购买 nike

我想使用枚举作为泛型结构的类型变体。

这给了我一个错误:

#[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`

Playground .

最佳答案

你不能那样做。枚举变体本身不是类型( there was an RFC for that ,而是 it was postponed )。

做这种事情的通常方法是有一个包含变体数据的结构,并使变体包含这个结构:

#[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);
}

您可以将枚举和结构与特征联系在一起。

关于rust - 如何将枚举变体用作通用类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72438594/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com