gpt4 book ai didi

string - 为什么我不能将两个字符串连接在一起,但我可以连接一个字符串和一个 &str?

转载 作者:行者123 更新时间:2023-12-05 01:03:40 25 4
gpt4 key购买 nike

The Rust Book, Chapter 4 under "Ways Variables and Data Interact: Clone"说您可以像这样使用 .clones2 设置为 s1

let s1 = String::from("hello");
let s2 = s1.clone();

println!("s1 = {}, s2 = {}", s1, s2);

为什么我不能把 s2 改成 s1.clone() + s1.clone()

let s1 = String::from("hello");
let s2 = s1.clone() + s1.clone();

println!("s1 = {}, s2 = {}", s1, s2);

当我尝试编译它时,我得到了

error[E0308]: mismatched types
--> src/main.rs:3:24
|
3 | let s2 = s1.clone() + s1.clone();
| ^^^^^^^^^^
| |
| expected `&str`, found struct `String`
| help: consider borrowing here: `&s1`

For more information about this error, try `rustc --explain E0308`.
error: could not compile `comment` due to previous error

我意识到我可以通过将 s1.clone() 更改为 &s1.clone() 来修复第二部分,但为什么需要这样做?

最佳答案

Add instance for strings左边有一个String,右边有一个&str。这会消耗左侧的字符串,并使用右侧的字符串(的副本)对其进行扩展。这样做是出于效率原因,以避免在每种情况下都必须复制两个字符串。

所以当你想在 Rust 中用 + 连接两个字符串时,左侧需要是 String(拥有的字符串),右侧需要side 需要是一个 &str (借用的字符串切片)。所以考虑

let s2 = s1.clone() + &s1.clone();

或者,因为我们是借用它,所以根本不需要第二个克隆。

let s2 = s1.clone() + &s1;

关于string - 为什么我不能将两个字符串连接在一起,但我可以连接一个字符串和一个 &str?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73889220/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com