let mut item = vec!["2", "3", "5"];
我想连接此向量的第一个索引和第二个索引,并替换为零索引的值。
item[0] = item[0] + item[1];
但是由于向量元素的类型是
&str
,并且在连接后得到的结果是String
,Rust不允许我更新向量的值。
最佳答案
获得结果的一种方法是通过编译器驱动开发。
从...开始:
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);
}
我们有:
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];
| ^^^^^^^^^^^^^^^^^^
遵循编译器建议:
item[0] = item[0].to_owned() + item[1];
现在我们得到:
|
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])`
然后再次应用建议:
|
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
现在,问题与生存期范围有关,遵循编译器的建议,这是最终版本:
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);
}
编译器已经提出了解决方案,但是在每种情况下,您都必须仔细考虑这是否满足您的应用程序要求。
在这种情况下,您必须注意生命周期范围。
如已经建议的,另一个更惯用的解决方案可以是使用String的Vec:
let mut item: Vec<String> = vec!["2".to_owned(), "3".to_owned(), "5".to_owned()];
item[0] = format!("{}{}", item[0], item[1]);
关于string - 如何连接Rust Vector的两个 `&str`类型元素并将其添加到零索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59207527/