gpt4 book ai didi

rust - &str 和字符串有什么区别

转载 作者:行者123 更新时间:2023-12-02 18:18:33 33 4
gpt4 key购买 nike

我正在浏览 Microsoft 的 Rust 教程 here , 这是关于

implement the copy_and_return function so that it returns a referenceto the value inserted in the vector

给出了解决方案 here , 但它与我的不同之处在于它使用 &String 作为返回类型,而我使用 &str。

// standard solution
fn copy_and_return<'a>(vector: &'a mut Vec<String>, value: &'a str) -> &'a String {
vector.push(String::from(value));
vector.get(vector.len() - 1).unwrap()
}
// my solution
fn copy_and_return<'a>(vector: &'a mut Vec<String>, value: &'a str) -> &'a str {
vector.push(String::from(value));
return value; // simply return value
}

fn main() {
let name1 = "Joe";
let name2 = "Chris";
let name3 = "Anne";

let mut names = Vec::new();

assert_eq!("Joe", copy_and_return(&mut names, &name1));
assert_eq!("Chris", copy_and_return(&mut names, &name2));
assert_eq!("Anne", copy_and_return(&mut names, &name3));

assert_eq!(
names,
vec!["Joe".to_string(), "Chris".to_string(), "Anne".to_string()]
)
}

除了返回类型之外,我的和标准方案的另一个区别是我只是简单地返回了参数value,而标准方案使用了复杂的方式vector.get(vector. len() - 1).unwrap().

我想知道教程采用另一种方式的解决方案是否有任何问题?


虽然@Masklinn 对我的问题提供了一个很好的答案,但它有点特定于我给出的示例,但没有直接解决标题 What is the difference between &str and &String
我找到了 this discussion非常有用:

Basically a String wraps and manages a dynamically allocated str as backing storage.Since str cannot be resized, String will dynamically allocate/deallocate memory.A &str is thus a reference directly into the backing storage of the String, while &String is a reference to the “wrapper” object.Additionaly, &str can be used for substrings, i.e. they are slices. A &String references always the whole string.

Chapter 4.3 Rust 书的内容也有帮助

最佳答案

I'm wondering if there's anything wrong with my solution that the tutorial takes another way?

我不认为这本身有什么问题,你的甚至可能更匹配函数名称,具体取决于它的解释方式:你应该复制并返回原件,还是复制并返回副本?你的是第一选择,他们的是第二。

它与生命周期无关,但这确实对程序行为产生了影响:在“官方”解决方案中,结果是对插入到 Vec 中的值的引用,这意味着它将只要向量是“活的”(至少假设向量没有被修改)。

如果将 value: &'a str 替换为 value: &'_ str(又名“你不关心的一生,但与 'a 不同):官方解决方案仍然可以编译,而你的则不能。

不过请注意,官方也可以返回 &'a str 而不管:

fn copy_and_return<'a>(vector: &'a mut Vec<String>, value: &'_ str) -> &'a str {
vector.push(String::from(value));
vector.get(vector.len() - 1).unwrap()
}

官方的解决方案很难通过例如

vector.get(vector.len() - 1)

是一种复杂的写法

vector.last()

但他们可能只是不想用高级 API 之类的东西让读者不知所措,我不能说。

关于rust - &str 和字符串有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71203874/

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