From the documentation: From<T> for U implies Into<U> for T. Everyone uses let x = String::from(z); meaning we have From<&str> for String and thus we should have Into<String> for &str.
However, the following does not work:
fn main() {
let z = "abc";
let x = String::from(z);
let s = &str::into(z);
}
What am I not understanding?
It works, except that &str::into(z) is understood as &(str::into(z)). If you want to call the associated function into for type &str, you must use a qualified name for that type:
fn main() {
let z = "abc";
let x = String::from(z);
let s: String = <&str>::into(z);
}
Note that the type annotation String was added because otherwise Rust cannot know which type is the target of into.
Otherwise, you can also use the method syntax
let s: String = z.into();
or the associated function of trait Into:
let s: String = Into::into(z);
You got turned around there a bit. Happens to me a lot with the whole to and from ;)
Let's consider the types. x is String. So into(x) would attempt to turn a String into a &str, and you can't do that like this.
The fact that String implements From<&str> means that &str implements Into<String>, i.e., you can turn a &str into a String.
Here's what you really want:
fn main() {
let x: &str = "abc";
let z: String = String::from(x);
let s: String = x.into();
}
No problem there!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With