[英]String concatenation in rust and borrowing
I have been learning rust recently.最近一直在学习rust。
And I stumbled upon a snippet that is really bugging me.我偶然发现了一个真正困扰我的片段。
Why does this work为什么这行得通
fn main() {
let s1 = String::from("Hello, ");
let s2 = String::from("world!");
let s3 = s1 + &s2;
println!("{}",s3)
}
And this does not?这不是吗?
fn main() {
let s1 = String::from("Hello, ");
let s2 = String::from("world!");
let s3 = &s1 + s2;
println!("{}",s3)
}
Thank you in advance先感谢您
From a technical standpoint, it's because String
implements Add<&str>
and Deref<Target=str>
.从技术角度来看,这是因为
String
实现了Add<&str>
和Deref<Target=str>
。 So the compiler can rewrite your first example, s1 + &s2
, into s1.add (s2.deref())
.因此编译器可以将您的第一个示例
s1 + &s2
重写为s1.add (s2.deref())
。
However neither &String
nor &str
implement Add
, so the compiler can't rewrite &s1 + …
into (&s1).add (…)
.但是
&String
和&str
都没有实现Add
,因此编译器无法将&s1 + …
重写为(&s1).add (…)
。
From a language design standpoint, this choice was made because s1 + …
may be done without allocation if there is enough space already allocated after the current contents of s1
, but &s1 + …
would always require an allocation and it was decided to make that allocation explicit.从语言设计的角度来看,做出这个选择是因为
s1 + …
如果在s1
的当前内容之后已经分配了足够的空间,则可以在不分配的情况下完成,但是&s1 + …
总是需要分配,因此决定进行分配明确的。 If you want to keep using the original s1
after the operation, you need to either clone it explicitly:如果您想在操作后继续使用原始
s1
,则需要显式克隆它:
let s3 = s1.clone() + &s2;
or if performance is really that critical, you need to pre-allocate enough memory to hold the result:或者如果性能真的那么关键,您需要预先分配足够的 memory 来保存结果:
let s3 = String::with_capacity (s1.len() + s2.len()) + &s1 + &s2;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.