HiveBrain v1.2.0
Get Started
← Back to all entries
snippetrustCritical

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
conditionallyenumhowcheckvariantoneanother

Problem

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 {
    if /* Memory */ {
        //..........
    } else if /* RocksDB */ {
        //..........
    }
}

Solution

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:

  • How to compare enum without pattern matching



  • Read from an enum without pattern matching



  • Compare enums only by variant, not value



  • https://doc.rust-lang.org/std/macro.matches.html

Context

Stack Overflow Q#51429501, score: 128

Revisions (0)

No revisions yet.