如何连接 Rust Vector 的两个“&str”类型元素并添加到零索引

Bas*_*Ali 7 string vector concatenation string-literals rust

let mut item = vec!["2", "3", "5"];
Run Code Online (Sandbox Code Playgroud)

我想连接该向量的第一个和第二个索引并替换为零索引的值。

item[0] = item[0] + item[1];
Run Code Online (Sandbox Code Playgroud)

但由于向量元素的类型&str以及连接后得到的结果是String,Rust 不允许我更新向量的值。

att*_*ona 9

获得结果的一种方法是通过编译器驱动开发。

从...开始:

fn main() {
   let mut item = vec!["2","3","5"];

   let first_item = &(item[0].to_owned() + item[1]);

   item[0] = item[0] + item[1];

   println!("item {:?}", item);
}
Run Code Online (Sandbox Code Playgroud)

我们有:

error[E0369]: binary operation `+` cannot be applied to type `&str`
 --> src/main.rs:6:22
  |
6 |    item[0] = item[0] + item[1];
  |              ------- ^ ------- &str
  |              |       |
  |              |       `+` cannot be used to concatenate two `&str` strings
  |              &str
  |
help: `to_owned()` can be used to create an owned `String` from a string reference. String concatenation appends the string on the right to the string on the left and may require reallocation. This requires ownership of the string on the left
  |
6 |    item[0] = item[0].to_owned() + item[1];
  |              ^^^^^^^^^^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)

按照编译器的建议:

item[0] = item[0].to_owned() + item[1];
Run Code Online (Sandbox Code Playgroud)

现在我们得到:

  |
6 |    item[0] = item[0].to_owned() + item[1];
  |              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |              |
  |              expected `&str`, found struct `std::string::String`
  |              help: consider borrowing here: `&(item[0].to_owned() + item[1])`
Run Code Online (Sandbox Code Playgroud)

然后再次应用该建议:

  |
6 |    item[0] = &(item[0].to_owned() + item[1]);
  |               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^- temporary value is freed at the end of this statement
  |               |
  |               creates a temporary which is freed while still in use
7 | 
8 |    println!("item {:?}", item);
  |                          ---- borrow later used here
Run Code Online (Sandbox Code Playgroud)

现在问题与生命周期范围有关,根据编译器的建议,这是最终版本:

fn main() {
   let mut item = vec!["2","3","5"];

   let first_item = &(item[0].to_owned() + item[1]);

   item[0] = first_item;

   println!("item {:?}", item);
}
Run Code Online (Sandbox Code Playgroud)

编译器已经驱动了一个解决方案,但在每种情况下,您都必须仔细考虑这是否是满足您的应用程序要求的解决方案。在这种情况下,您必须注意生命周期范围。

正如已经建议的,另一个更惯用的解决方案可能是使用 String 的 Vec:

let mut item: Vec<String> = vec!["2".to_owned(), "3".to_owned(), "5".to_owned()];

item[0] = format!("{}{}", item[0], item[1]);
Run Code Online (Sandbox Code Playgroud)