【问题标题】:How do I conditionally check if an enum is one variant or another?如何有条件地检查枚举是否是一个变体?
【发布时间】:2018-12-27 23:54:23
【问题描述】:

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

enum DatabaseType {
    Memory,
    RocksDB,
}

为了在检查参数是DatabaseType::MemoryDatabaseType::RocksDB 的函数中设置条件if,我需要什么?

fn initialize(datastore: DatabaseType) -> Result<V, E> {
    if /* Memory */ {
        //..........
    } else if /* RocksDB */ {
        //..........
    }
}

【问题讨论】:

    标签: enums rust conditional


    【解决方案1】:

    首先,返回并重新阅读免费的官方 Rust 书籍The Rust Programming Language,特别是 the chapter on enums


    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 {
            // ...
        }
    }
    

    另见:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-16
      • 1970-01-01
      • 2020-08-13
      • 2015-02-12
      • 1970-01-01
      相关资源
      最近更新 更多