Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

[Rust Enums]: How to get data value from mixed type enum in rust?

Tags:

enums

rust

Hello I am new to rust and just exploring how to use enums. I have simple code which has enum.

#[derive(Debug)]
enum Thing {
    Str(String),
    Boolean(bool)
}

fn run() -> Vec<Thing> {
    let mut output: Vec<Thing> = Vec::new();
    output.push(Thing::Str("Hello".to_string()));
    output.push(Thing::Boolean(true));
    return output
}

fn main() {

    let result = run();
    for i in result {
        println!("{:?}", i)
    }
}

when I run this code it works fine but I am getting output like this

Str("Hello")
Boolean(true)

How can I get the values like

"Hello"
true

so I can use this values for further processing like concat the string or something similar.

Thanks for help.

like image 483
JNP Avatar asked Mar 01 '23 14:03

JNP


1 Answers

You are using the #[derive(Debug)] macro, which automatically defines the Debug trait for your type. When calling println!("{:?}", i). The {:?} is called a "print marker" and means "use the Debug trait for Debug formatting".

What you want to use is Display formatting, which requires a custom implementation of the Display trait.

First, implement Display for Thing:

use std::fmt;

impl fmt::Display for Thing {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
           Thing::Str(s) => write!(f, "{}", s),
           Thing::Boolean(b) => write!(f, "{}", b),
        }
    }
}

Then, you should be able to call:

println!("{}", i)

Which will use the Display trait instead of the Debug trait.

The Debug and Display examples from "Rust By Example" are good if you want to learn more about formatting traits.

like image 116
C-RAD Avatar answered Mar 07 '23 17:03

C-RAD