1

I have a match statement where I want to print the error, if it occurs. But, it seems it wont allow it due to the generic type:

match get_numeral(&str_inp).parse::<T>() {
    Ok(rslt) => {
        if rslt >= val_min && rslt <= val_max {
            str_inp = rslt.to_string();
            finish = true;
        }
    }
    Err(e) => (println!("{}", e)),
}

With the preceding code, the following error is displayed:

137 |             Err(e)=> (println!("{}",e)),
    |                                     ^ `<T as std::str::FromStr>::Err` cannot be formatted with the default
formatter

What am I missing here?

I did notice the following hints:

    = help: the trait `std::fmt::Display` is not implemented for `<T as std::str::FromStr>::Err`
    = note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead
    = help: consider adding a `where <T as std::str::FromStr>::Err: std::fmt::Display` bound
    = note: required by `std::fmt::Display::fmt`

My function definition looks like:

fn expect_val<T>(val_min: T, val_max: T, accept: Vec<String>) -> String
where
    T: std::str::FromStr + PartialOrd + ToString,

Reproducible example

STF_ZBR
  • 617
  • 1
  • 4
  • 19
  • 2
    You possibly want `::Err : std::error::Error`, i.e. force it to be the actual error object (which will always implement `Display`) and not something arbitrary. – Cerberus Dec 18 '19 at 05:59
  • If your error implements Debug, you could print that value instead: `println!("{:?}", e)` – Bennett Hardwick Dec 18 '19 at 13:13
  • It's hard to answer your question because it doesn't include a [MRE]. We can't tell what crates (and their versions), types, traits, fields, etc. are present in the code. It would make it easier for us to help you if you try to reproduce your error on the [Rust Playground](https://play.rust-lang.org) if possible, otherwise in a brand new Cargo project, then [edit] your question to include the additional info. There are [Rust-specific MRE tips](//stackoverflow.com/tags/rust/info) you can use to reduce your original code for posting here. Thanks! – Shepmaster Dec 18 '19 at 14:22
  • As the compiler tells you: ``consider adding a `where ::Err: std::fmt::Display` bound`` – Shepmaster Dec 18 '19 at 14:27
  • I added a reproducible example. Changing the Err to '_' vs 'e' will clear all errors. I have tried a to add the "where" bound, but I haven't been successful. Also, using '{:?}' doesn't improve the situation. – STF_ZBR Dec 18 '19 at 23:43

0 Answers0