Background
I know that in Rust, people prefer &str rather than &String . But in some cases we were only given &String .
For example, you call std::iter::Iterator::peekable . The return value is a Peekable<I> object that wraps the original iterator in it and gives you one additional peek method.
The thing is, peek gives you a reference to an iterator element. Therefore, if you have an iterator containing String s, in this case you have &String . Because of this, you can easily use as_str to get &str , but in the code I'll show below, it is equivalent to calling clone .
Question
This code
#[derive(Debug)] struct MyStruct(String); impl MyStruct { fn new<T>(t: T) -> MyStruct where T: Into<String>, { MyStruct(t.into()) } } fn main() { let s: String = "Hello world!".into(); let st: MyStruct = MyStruct::new(&s); println!("{:?}", st); }
does not compile because String does not implement From<&String> . This is not intuitive.
Why is this not working? Is this just a missing feature of the standard library, or are there some other reasons that impede the implementation of the standard library?
In real code, I only have a reference to String , and I know to make it work. I only need to call clone , but I want to know why.
source share