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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With