Access Enum Data

I was training Rust and came up with the following problem:

fn main() {
    #[derive(Debug)]
    enum SpreadSheetCell {
        Int(i32),
        Float(f64),
        Text(String),
    }
    
    let v = [
        SpreadSheetCell::Int(17),
        SpreadSheetCell::Float(1.77),
        SpreadSheetCell::Text(String::from("Graydon Hoare"))
    ];
    
    println!("{:?}", v[0]);
    println!("{:?}", v[1]);
    println!("{:?}", v[2]);
}

Output:

Int(17)
Float(1.77)
Text("Graydon Hoare")

The problem is that in the output, the code doesn't access the enum value directly
So, how can I access the enum values ​​directly?
In order to make the output look like this:

17
1.77
"Graydon Hoare"

You have to match on the enum in order to get the data out of the correct (active) variant. You can even impl Debug accordingly by hand:

impl Debug for SpreadSheetCell {
    fn fmt(&self, formatter: &mut Formatter) -> Result {
        match *self {
            SpreadSheetCell::Int(i) => i.fmt(formatter),
            SpreadSheetCell::Float(x) => x.fmt(formatter),
            SpreadSheetCell::Text(ref s) => s.fmt(formatter),
        }
    }
}
1 Like

Read Enums and Pattern Matching - The Rust Programming Language (rust-lang.org).

You have to (pattern) match, for example :

if let SpreadSheetCell::Text(text) = cell {
    println!("{}", text);
}

or :

match cell {
    SpreadSheetCell::Int(i) => {},
    SpreadSheetCell::Float(f) => {},
    SpreadSheetCell::Text(t) => {},
}
1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.