How to parse some string to most appropriate type?
I know there is .parse::<>()
method, but you need to specify type in advance like this:
fn main() {
let val = String::from("54");
assert_eq!(val.parse::<i32>().unwrap(), 54i32);
let val = String::from("3.14159");
assert_eq!(val.parse::<f32>().unwrap(), 3.14159f32);
let val = String::from("Hello!");
assert_eq!(val.parse::<String>().unwrap(), "Hello!".to_string());
}
But I need something like this:
fn main() {
let val = String::from("54");
assert_eq!(val.generic_parse().unwrap(), 54i32); // or 54i16 or 54 u32 or etc ...
let val = String::from("3.14159");
assert_eq!(val.generic_parse().unwrap(), 3.14159f32);
let val = String::from("Hello!");
assert_eq!(val.generic_parse().unwrap(), "Hello!".to_string());
}
Is there an appropriate crate for something like this? I don't want to re-invent the wheel for the umpteenth time.
EDIT
This is what I actually want to do:
struct MyStruct<T> {
generic_val: T,
}
fn main() {
let val = String::from("54");
let b = MyStruct {generic_val: val.parse().unwrap()};
let val = String::from("3.14159");
let b = MyStruct {generic_val: val.parse().unwrap()};
}
Error:
error[E0282]: type annotations needed for `MyStruct<T>`
--> src/main.rs:7:13
|
7 | let b = MyStruct {generic_val: val.parse().unwrap()};
| - ^^^^^^^^ cannot infer type for type parameter `T` declared on the struct `MyStruct`
| |
| consider giving `b` the explicit type `MyStruct<T>`, where the type parameter `T` is specified
assert_eq!
notparse
. The Rust compiler is capable of figuring out what type parameterparse
should take without you telling it. The problem is you have to tell it, and allassert_eq!
requires is that the types of its arguments be comparable with==
, not that they be the same. So is this exactly how you're using it, or if I suggest a fix that focuses onassert_eq!
will you say that doesn't work in your real code and you need something different? – trentclassert_eq!
as example. In real code,val
from this example will be copied to a generic in a struct.let a = MyStruct {generic_val: val.copy(), ...etc
or something like that – VitalijsMyStruct
? It's certainly possible to defer the choice ofT
until well after creatingMyStruct<T>
. Can you create a minimal reproducible example? – trentcl