Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.5k views
in Technique[技术] by (71.8m points)

Rust 字符串相加第二个参数为什么要是&str

    let s = String::from("asdasd");
    let v = String::from("asdasd");
    let _s2 = s + &v;

Rust 字符串相加第二个参数为什么要是&str


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
为什么是借用

如果不借用的话,第二个参数就会被移动,完成字符串拼接之后,v 就不可用。

但这很不实用,因为字符串拼接不可避免要复制 v 的内容,没必要移动 + 复制,直接借用 + 复制,这样后面还能继续用 v。

那为什么第一个参数不是借用呢?主要是为了性能优化,重用底层的数组,减少复制,把多个字符串串拼接的复杂度从 O(n^2) 优化到 O(n) ,原理类似 Java 的 StringBuilder。

为什么是 &str 而不是 &String

这是一个常用的模式: Use borrowed types for arguments

Using borrowed types you can avoid layers of indirection for those instances where the owned type already provides a layer of indirection. For instance, a String has a layer of indirection, so a &String will have two layers of indrection. We can avoid this by using &str instead, and letting &String coerce to a &str whenever the function is invoked.

主要是为了减少一层指针。(String 实现 Deref<Target=str>,所以在函数需要 &str 参数的时候,&String 自动强转换成 &str)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.5k users

...