I have an enum which implements From
taking various types, but I'm having trouble getting the correct implementation of the corresponding into
method. An example:
enum Value {
Integer(i64),
Float(f64),
String(String),
}
impl From<i64> for Value {
fn from(value: i64) -> Self {
Value::Integer(value)
}
}
impl From<f64> for Value {
fn from(value: f64) -> Self {
Value::Float(value)
}
}
impl From<String> for Value {
fn from(value: String) -> Self {
Value::String(value)
}
}
impl From<&str> for Value {
fn from(value: &str) -> Self {
Value::String(value.to_string())
}
}
fn main() {
let v = Value::from("foo");
// assert_eq!("foo".to_string(), v.into());
/*
* The above fails:
*
error[E0282]: type annotations needed
--> src/main.rs:35:37
|
35 | assert_eq!("foo".to_string(), v.into());
| --^^^^--
| | |
| | cannot infer type for type parameter `T`
| this method call resolves to `T`
*/
// assert_eq!("foo".to_string(), v.into::<String>());
/*
* The above fails:
*
error[E0107]: wrong number of type arguments: expected 0, found 1
--> src/main.rs:48:44
|
48 | assert_eq!("foo".to_string(), v.into::<String>());
| ^^^^^^ unexpected type argument
*/
assert_eq!("foo".to_string(), v.into<String>());
/*
* The above fails:
*
error: chained comparison operators require parentheses
--> src/main.rs:58:41
|
58 | assert_eq!("foo".to_string(), v.into<String>());
| ^^^^^^^^
|
help: use `::<...>` instead of `<...>` to specify type arguments
|
58 | assert_eq!("foo".to_string(), v.into::<String>());
| ^^
*/
}
Errors:
Compiling playground v0.0.1 (/playground)
error: chained comparison operators require parentheses
--> src/main.rs:58:41
|
58 | assert_eq!("foo".to_string(), v.into<String>());
| ^^^^^^^^
|
help: use `::<...>` instead of `<...>` to specify type arguments
|
58 | assert_eq!("foo".to_string(), v.into::<String>());
| ^^
error: aborting due to previous error
error: could not compile `playground`.
To learn more, run the command again with --verbose.
Notice how for the last example (line 58) the error message suggests using the form v.into::<String>()
, which is what I used on line 48, but that led to an E0107 error.