I am trying to write a generic function which will try to convert a string to a number type like i32
, f64
etc. If the string is not convertible then it will return 0
. I am looking for an appropriate trait bound to use in my generic function below:
use std::str::FromStr;
fn get_num_from_str<T: FromStr>(maybe_num_str: &String) -> T {
let maybe_num = T::from_str(maybe_num_str.as_str());
if maybe_num.is_ok() {
return maybe_num.unwrap();
}
0 as T
}
fn main() {
let num_str = String::from("12");
println!("Converted to i32: {}", get_num_from_str::<i32>(&num_str));
}
I found that Rust had a Primitive
trait before which was removed. Is there something else now that can be used instead?
I have found a workaround:
use std::str::FromStr;
fn get_num_from_str<T: Default + FromStr>(maybe_num_str: &String) -> T {
let maybe_num = T::from_str(maybe_num_str.as_str());
maybe_num.unwrap_or(Default::default())
}
This, as the trait bound suggests, should work for anything which has implementations for both Default
and FromStr
and I should rename the function to reflect that, but it would still be nice to know if there is any trait for the primitive number types only which I can use to make sure this function cannot be used for anything other than the number types.