我知道,在魯斯特人喜歡&str
而非&String
。但在某些情況下,我們只給予&String
。
一個例子是當你撥打std::iter::Iterator::peekable
。返回值是一個Peekable<I>
對象,它將原始迭代器封裝到它中,併爲您提供一個額外的方法peek
。
這裏的關鍵是peek
只給你一個迭代器項的引用。所以如果你有一個包含String
的迭代器,在這種情況下你只有&String
。因爲,你可以很容易地使用as_str
得到一個&str
,但在我將在下面顯示的代碼相當於撥打clone
。
問題
此代碼
#[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);
}
不編譯,因爲String
沒有實現From<&String>
。這不直觀。
爲什麼這不起作用?它只是標準庫的一個缺失功能,還有一些其他原因會阻止標準庫實現它?
在真實的代碼中,我只有一個參考String
,我知道使它工作,我只需要撥打clone
來代替,但我想知道爲什麼。
我不會說這是反直覺的 - 其它對象不做,要麼,例如'Vec'不'impl來自<&Vec>';也'impl <'a>從<&'a str>'是一個更可能的用例,它很容易獲得。 –
ljedrz
我覺得真正的答案與我的相關問題有關https://stackoverflow.com/questions/45126120/if-intostring-not-implemented-for-string-why-these-implementations-are-co –