简体   繁体   English

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

[英]How can I concatenate two `&str` type elements of Rust Vector and add to Zero Index

let mut item = vec!["2", "3", "5"];

I want to concatenate the first and second index of this vector and replace with the value of zero index.我想连接这个向量的第一个和第二个索引并用零索引的值替换。

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

But due to the type of vector elements being &str and the result I'm getting after concatenation is String , Rust is not letting me update the value of vector.但是由于向量元素的类型是&str并且我在连接后得到的结果是String ,Rust 不允许我更新向量的值。

One way to get to the result is through Compiler Driven Development.获得结果的一种方法是通过编译器驱动开发。

Starting with:从...开始:

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);
}

We have:我们有:

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];
  |              ^^^^^^^^^^^^^^^^^^

Following the compiler suggestion:按照编译器的建议:

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

Now we get:现在我们得到:

  |
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])`

Then applying again the suggestion:然后再次应用该建议:

  |
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

Now the problem is related to lifetime scopes, following the compiler suggestion this is the final version:现在问题与生命周期范围有关,按照编译器的建议,这是最终版本:

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);
}

The compiler has driven to a solution, but in every case you have to carefully consider if this is a solution that meets the requirements of your application.编译器已经找到了解决方案,但在每种情况下,您都必须仔细考虑该解决方案是否满足您的应用程序的要求。 In this case you must pay attention to lifetime scopes.在这种情况下,您必须注意生命周期范围。

Another, more idiomatic solution, as already suggested, could be to use a Vec of String:正如已经建议的那样,另一个更惯用的解决方案可能是使用字符串的 Vec:

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

item[0] = format!("{}{}", item[0], item[1]);

Assuming you want to do it in runtime, it is not possible.假设您想在运行时执行此操作,这是不可能的。 &str is non-owning type, one can't concatenate two &str 's into one for the storage they point to may be non-contigious. &str是非拥有类型,不能将两个&str连接成一个,因为它们指向的存储可能是非连续的。

You may achieve the goal using String :您可以使用String实现目标:

let mut item = vec![String::from("2"), String::from("3"), String::from("5")];
// Vec is not empty and contains more than 1 element, it is safe to unwrap
let (first, rest) = item.split_first_mut().unwrap();
// Append the second element to the end of the first element 
first.push_str(rest[0].as_str()); 
println!("{}", &first); // 23

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我们如何在特定分隔符之前连接向量元素并在 Rust 中创建新向量 - How can we Concatenate vector elements before specific separator and make new vector in Rust 如何将整数向量的元素连接到 C++ 中的字符串? - How can I concatenate the elements of a vector of integers to a string in C++? 如何连接 str 和 int 对象? - How can I concatenate str and int objects? 如何在 Rust 中将字符串转换为向量? - How can I convert a String into a Vector in Rust? 为什么我不能将两个字符串连接在一起,但我可以连接一个字符串和一个 &str? - Why can't I concatenate two Strings together, but I can concatenate a String and a &str? 如何在Rust中将&str转换为~str? - How do I transform &str to ~str in Rust? TypeError: can only concatenate str (not &quot;tuple&quot;) to str 我该如何解决这个问题? - TypeError: can only concatenate str (not "tuple") to str How do i fix this? 第一次使用编码python,我如何解决只能将str(而不是“int”)连接到str的问题 - First time using coding python, how I fix the can only concatenate str (not "int") to str 如果 Rust str 是不可变的,为什么我可以将 str 变量声明为可变的? - Why can I declare a str variable as mutable if Rust str is immutable? 如何在 Rust 中将一串数字转换为整数数组或向量? - How can I convert a string of numbers to an array or vector of integers in Rust?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM