如何有条件地检查枚举是一个变体还是另一个变体? [英] How do I conditionally check if an enum is one variant or another?

查看:63
本文介绍了如何有条件地检查枚举是一个变体还是另一个变体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an enum with two variants:

enum DatabaseType {
    Memory,
    RocksDB,
}

如果要在有条件的函数中进行检查,则需要什么条件如果参数是 DatabaseType :: Memory DatabaseType :: RocksDB

What do I need in order to make a conditional if inside a function that checks if an argument is DatabaseType::Memory or DatabaseType::RocksDB?

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


推荐答案

首先,返回并重新阅读一本免费的Rust官方书 Rust编程语言 ,特别是有关枚举的章节

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



if let



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

另请参见:

  • How to compare enum without pattern matching
  • Read from an enum without pattern matching
  • Compare enums only by variant, not value

这篇关于如何有条件地检查枚举是一个变体还是另一个变体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆