如何使用枚举变体作为泛型类型?

Ama*_*rma 2 rust rust-cargo

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

这给了我一个错误:

#[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);
}
Run Code Online (Sandbox Code Playgroud)
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`
Run Code Online (Sandbox Code Playgroud)

游乐场

Cha*_*man 12

你不能这样做。枚举变体本身并不是类型(有一个 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);
}
Run Code Online (Sandbox Code Playgroud)

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

  • 我不确定您的示例中“enum”的作用是什么。据我了解,它从未被使用过。我错过了什么吗? (4认同)