Are there alternative better ways for multiple `Box::new(something) as Box<dyn std::fmt::Display>` in `match`?

I am learning Rust and have passed the following codes:

// Code 1. A similar code with an error posted at https://users.rust-lang.org/t/returning-different-types-in-match-arms/73508?u=paalon
// error[E0308]: `match` arms have incompatible types
fn main() {
    let x = 1;
    let z = match x {
        1 => 0,
        2 => 3.14,
        _ => "others",
    };
    println!("{}", z);
}
// Code 2. A solution posted at https://users.rust-lang.org/t/returning-different-types-in-match-arms/73508/6?u=paalon
fn main() {
    let x = 1;
    let z: Box<dyn std::fmt::Display> = match x {
        1 => Box::new(0),
        2 => Box::new(3.14),
        _ => Box::new("others"),
    };
    println!("{}", z);
}
// Code 3. What I want to do but with an error
// error[E0308]: `match` arms have incompatible types
fn main() {
    let x = 1;
    println!("{}", match x {
        1 => Box::new(0),
        2 => Box::new(3.14),
        _ => Box::new("others"),
    });
}
// Code 4. A solution posted at https://users.rust-lang.org/t/how-to-return-box-dyn-mytrait-from-match-arms-without-variable/93060/2?u=paalon
fn main() {
    let x = 1;
    println!("{}", match x {
        1 => Box::new(0) as Box<dyn std::fmt::Display>,
        2 => Box::new(3.14) as Box<dyn std::fmt::Display>,
        _ => Box::new("others") as Box<dyn std::fmt::Display>,
    });
}

The code 4 can do what I want but it seems a bit redundant because it has many Box::new(something) as Box<dyn std::fmt::Display>. Is there a better way?

You only need the first cast for #4.

2 Likes

You can replace all of the Boxes with & to make it more efficient.

2 Likes

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.