如何有条件地检查枚举是否是一种变体?

问题描述 投票:0回答:3

我有一个有两个变体的枚举:

enum DatabaseType {
    Memory,
    RocksDB,
}

我需要什么才能在函数内创建一个条件 if 来检查参数是否是

DatabaseType::Memory
DatabaseType::RocksDB

fn initialize(datastore: DatabaseType) -> Result<V, E> {
    if /* Memory */ {
        //..........
    } else if /* RocksDB */ {
        //..........
    }
}
enums rust conditional-statements
3个回答
106
投票

首先看一下免费的官方 Rust 书籍 Rust 编程语言,特别是关于枚举的章节


match

fn initialize(datastore: DatabaseType) {
    match datastore {
        DatabaseType::Memory => {
            // ...
        }
        DatabaseType::RocksDB => {
            // ...
        }
    }
}

if let

fn initialize(datastore: DatabaseType) {
    if let DatabaseType::Memory = datastore {
        // ...
    } else {
        // ...
    }
}

==

#[derive(PartialEq)]
enum DatabaseType {
    Memory,
    RocksDB,
}

fn initialize(datastore: DatabaseType) {
    if DatabaseType::Memory == datastore {
        // ...
    } else {
        // ...
    }
}

matches!

自 Rust 1.42.0 起可用

fn initialize(datastore: DatabaseType) {
    if matches!(datastore, DatabaseType::Memory) {
        // ...
    } else {
        // ...
    }
}

另请参阅:


2
投票
// A simple example that runs in rust 1.58:
enum Aap {
    Noot(i32, char),
    Mies(String, f64),
}

fn main() {
    let aap: Aap = Aap::Noot(42, 'q');
    let noot: Aap = Aap::Mies(String::from("noot"), 422.0);
    println!("{}", doe(aap));
    println!("{}", doe(noot));
}

fn doe(a: Aap) -> i32 {
    match a {
        Aap::Noot(i, _) => i,
        Aap::Mies(_, f) => f as i32,
    }
}

0
投票

从 Rust 1.21.0 开始,您可以使用 std::mem::discriminant 来检查枚举变量而不是按值:

use std::mem;

enum Foo { A(&'static str), B(i32), C(i32) }

assert_eq!(mem::discriminant(&Foo::A("bar")), mem::discriminant(&Foo::A("baz")));
© www.soinside.com 2019 - 2024. All rights reserved.