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

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

问题描述

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

I have an enum with two variants:

enum DatabaseType {
    Memory,
    RocksDB,
}

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

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

如果让

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

匹配!

这从 Rust 1.42.0 开始可用

matches!

This is available since Rust 1.42.0

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

另见:

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

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