Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

rust - 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 */ {
        //..........
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...