[英]join a string vector in rust
I want to join a string vector into a String
, but I got confused on the different result of vector of &str
&String
String
:我想将一个字符串向量加入一个String
,但我对&str
&String
String
向量的不同结果感到困惑:
let v1: Vec<String> = vec!["foo".to_string(), "bar".to_string()];
println!("{:?}", v1.join(",")); // OK
let v2: Vec<&str> = vec!["foo", "bar"];
println!("{:?}", v2.join(",")); // OK
let foo = "foo".to_string();
let bar = "bar".to_string();
let v3: Vec<&String> = vec![&foo, &bar];
println!("{:?}", v3.join(",")); // error
Here's the error:这是错误:
error[E0599]: no method named `join` found for type `std::vec::Vec<&std::string::String>` in the current scope
--> src/main.rs:11:21
|
11 | println!("{:?}", v3.join(",")); // error
| ^^^^ method not found in `std::vec::Vec<&std::string::String>`
Any help and explanation is really welcome非常欢迎任何帮助和解释
In general, using a &String
is discouraged: if you need an owned copy, use a String
and if you need a reference, use an &str
.一般来说,不鼓励使用&String
:如果您需要拥有的副本,请使用String
,如果您需要引用,请使用&str
。 Automatic dereferencing allows this to be reasonably transparent:自动取消引用允许这相当透明:
let foo: String = "foo".to_string();
let bar: String = "bar".to_string();
let v3: Vec<&str> = vec![&foo, &bar];
Note: In the above code, you don't really need to write the types explicitly, but I put them in to show that a Vec<&str>
can be built transparently from references to variables of type String
.注意:在上面的代码中,您实际上并不需要显式地编写类型,但我将它们放入以表明Vec<&str>
可以从对String
类型变量的引用透明地构建。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.