Rust 書,第 4 章“變數和資料互動方式:克隆”下說您可以使用.clone設定s2為s1這樣
let s1 = String::from("hello");
let s2 = s1.clone();
println!("s1 = {}, s2 = {}", s1, s2);
為什么我不能s2改成s1.clone() s1.clone()
let s1 = String::from("hello");
let s2 = s1.clone() s1.clone();
println!("s1 = {}, s2 = {}", s1, s2);
當我嘗試編譯它時,我得到
error[E0308]: mismatched types
--> src/main.rs:3:24
|
3 | let s2 = s1.clone() s1.clone();
| ^^^^^^^^^^
| |
| expected `&str`, found struct `String`
| help: consider borrowing here: `&s1`
For more information about this error, try `rustc --explain E0308`.
error: could not compile `comment` due to previous error
s1.clone()我意識到我可以通過更改為來修復第二部分&s1.clone(),但為什么需要這樣做?
uj5u.com熱心網友回復:
字串的Add實體String在左側采用 a ,&str在右側采用 a。這會消耗左側的字串,并使用右側的字串(的副本)對其進行擴展。出于效率原因,這樣做是為了避免在每種情況下都必須復制兩個字串。
所以當你想在 Rust 中用 連接兩個字串時 ,左側需要是一個String(擁有的字串),而右側需要是一個&str(借用的字串切片)。所以考慮
let s2 = s1.clone() &s1.clone();
或者,因為我們是借用它,所以根本不需要第二個克隆。
let s2 = s1.clone() &s1;
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/510258.html
標籤:细绳锈级联
上一篇:如何通過在java中創建自己的方法來計算字串中的特定出現次數和字母
下一篇:將字串文字添加到已初始化的變數
