[英]How to concatenate two strings into the third string without copying?
我是 Rust 的新手,我目前正在閱讀 Rust 編程語言書。
我很好奇這個例子:
fn main() {
let s1 = String::from("Hello, ");
let s2 = String::from("world!");
let s3 = s1 + &s2; // note s1 has been moved here and can no longer be used
}
是否有可能不僅獲得s1
的所有權,而且也獲得s2
的所有權,因此s2
和s1
都被無效化,從而使s3
成為唯一可能保持可用的變量?
更新的答案
這是不可能的。 String
必須是 memory 中的單個連續分配。 如果您想推出自己的簡單解決方案,您可以定義如下類型:
struct MyString {
parts: Vec<String>,
}
impl MyString {
fn concat(&mut self, other: String) {
self.parts.push(other);
}
}
但是,為這種自定義類型重新實現每個有用的String
方法將是乏味且容易出錯的。 您可以找到實現Rope 數據結構的 Rust 板條箱,並且an-rope似乎是這樣的板條箱,但僅支持一小部分String
方法。
當我將 OP 的問題解釋為關於無效和移動變量的問題時,我給出了這個答案:
原始答案
您可以通過將任何非Copy
變量移動到其他位置來使其無效,例如將其傳遞給drop
function:
fn main() {
let s1 = String::from("Hello, ");
let s2 = String::from("world!");
let s3 = s1 + &s2; // s1 invalidated
drop(s2); // s2 invalidated
// now only s3 is usable
}
如果這是您的應用程序中的常見模式,您可以編寫一個 function ,它擁有 2 個String
的所有權並返回連接結果:
fn concat(s1: String, s2: String) -> String {
s1 + &s2
}
fn main() {
let s1 = String::from("Hello, ");
let s2 = String::from("world!");
let s3 = concat(s1, s2); // s1 & s2 invalidated
// now only s3 is usable
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.