简体   繁体   中英

How do I conditionally check if an enum is one variant or another?

I have an enum with two variants:

enum DatabaseType {
    Memory,
    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 */ {
        //..........
    }
}

First, go back and re-read the free, official Rust book : The Rust Programming Language , specifically 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 {
        // ...
    }
}

See also:

// 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,
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM