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

First have a look at 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 {
        // ...
    }
}

matches!

This is available since Rust 1.42.0

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

See also:

Leave a Comment