Println! question

Hello, forgive me this question....just starting.
The code below does not compile. The error lies in the pirint statement:
"no field XFloat on type `SpreadsheetCell"
I want to print the float value in the vector.

fn main() {
    

enum SpreadsheetCell {
    XInt(i32),
    XFloat(f64),
    XText(String),
}

let mut row = vec![
    SpreadsheetCell::XInt(3),
    SpreadsheetCell::XText(String::from("blue")),
    SpreadsheetCell::XFloat(10.12),
];

row[1] = SpreadsheetCell::XFloat(2.1);

println!("Array {}", row[2].XFloat);

} 

Many thanks
SheiksBeer

That syntax is invalid. You cannot access enum variants like that; you might be interested in learning about pattern matching.

1 Like

You might want this.

use std::fmt::Display;
impl Display for SpreadsheetCell {
    fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            fmt,
            "{}",
            match self {
                Self::XInt(int) => int as &dyn Display,
                Self::XFloat(float) => float as _,
                Self::XText(string) => string as _,
            }
        )
    }
}
2 Likes

Thanks a lot, because writing

println!("Array {}", row[1]);

results in the compiler error

`SpreadsheetCell` doesn't implement `std::fmt::Display`

I was already looking for ways to implement std::fmt::Display.

best regards

1 Like

You can use the debug implementation to help you with that, since it can be easily derived:

#[derive(Debug)]
enum SpreadsheetCell {
    XInt(i32),
    XFloat(f64),
    XText(String),
}

...

// Note that now you can use the :? to use the debug implementation in the println macro:
println!("Array {:?}", row[1]);

1 Like

Cool. It works.
Obviously I have to dig into the #[derive(Debug)] directive.

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.