Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 */ {
        //..........
    }
}
like image 906
Moreorem Avatar asked Jul 19 '18 18:07

Moreorem


People also ask

How do you check if a value is in an enum Python?

To check if a value exists in an enum in Python: Use a list comprehension to get a list of all of the enum's values. Use the in operator to check if the value is present in the list. The in operator will return True if the value is in the list.

How do I get enum value in Rust?

Bookmark this question. Show activity on this post. struct Point { x: f64, y: f64, } enum Shape { Circle(Point, f64), Rectangle(Point, Point), } let my_shape = Shape::Circle(Point { x: 0.0, y: 0.0 }, 10.0);


1 Answers

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

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
like image 176
Shepmaster Avatar answered Oct 19 '22 20:10

Shepmaster