58

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 */ {
        //..........
    }
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Craftrac
  • 753
  • 1
  • 7
  • 13

2 Answers2

101

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:

Danvil
  • 22,240
  • 19
  • 65
  • 88
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
2
// 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,
    }
}
ruud
  • 21
  • 4
  • 1
    I don't know if you want to modify your example, but it's worth pointing out that if one of the variants is a struct with named fields (say, `Noot { a: i32, b: char }`) then one matches using `..` instead of `_`. – John Perry Aug 09 '22 at 03:43