gpt4 book ai didi

rust - 影子变量在 Rust 中不起作用,给出生命周期错误

转载 作者:行者123 更新时间:2023-12-05 03:28:43 24 4
gpt4 key购买 nike

这是我的代码片段:

pub fn abbreviate(mut phrase: &str) -> String {
let mut tla = String::new();
phrase = phrase.replace("-", "");
}

给出这个错误

1 | pub fn abbreviate(mut phrase: &str) -> String {
| ---- expected due to this parameter type
...
4 | phrase = phrase.replace("-", "");
| ^^^^^^^^^^^^^^^^^^^^^^^
| |
| expected `&str`, found struct `String`
| help: consider borrowing here: `&phrase.replace("-", "")`

如果我听从建议

pub fn abbreviate(mut phrase: &str) -> String {
let mut tla = String::new();
phrase = &phrase.replace("-", "");
}

我得到了这个生命周期编译错误

1 | pub fn abbreviate(mut phrase: &str) -> String {
| - let's call the lifetime of this reference `'1`
...
4 | phrase = &phrase.replace("-", "");
| ----------^^^^^^^^^^^^^^^^^^^^^^^- temporary value is freed at the end of this statement
| | |
| | creates a temporary which is freed while still in use
| assignment requires that borrow lasts for `'1`

这有效但很丑:

pub fn abbreviate(mut phrase: &str) -> String {
let mut tla = String::new();
let phrase2 = &phrase.replace("-", "");
}

为什么我不能隐藏 phrase 变量?有人可以解释上面关于生命周期的编译器错误吗?

最佳答案

&str 是一个字符串切片,它引用保存在别处的数据。在字符串文字的情况下,您有一个 &'static str,它是对二进制文件本身中保存的数据的引用。否则,您通常会通过获取现有 String 的一部分来生成 &str

如果您要在运行时生成新字符串,最直接的方法是制作一个String。然后您可以从中分配切片 (&str),但是 String 值本身必须至少与切片一样长。 &phrase.replace("-", "") 在这里不起作用,因为您正在获取 temporary 的一部分 - 一个仅存在的值它所属的声明。此语句结束后,replace 方法返回的临时 String 将被删除,phrase 将引用指向字符串的切片不再存在,并且借用检查器正确地指出这不是内存安全的。这就像在同一函数中返回对保存在局部变量中的值的引用。

但是,您在这里所做的甚至不是阴影,您只是试图从不兼容的类型中重新分配一个变量。使用同名的新变量隐藏名称 phrase 将允许新名称具有不同的类型(例如 String),因此这是有效的:

pub fn abbreviate(phrase: &str) -> String {
let mut tla = String::new();
// phrase refers to a &str here
let phrase = phrase.replace("-", "");
// phrase refers to a String here

// Return something
}

基本上,您的第一个示例失败只是因为您没有在赋值之前放置 let

另请注意,phrase 参数在这里不需要是mutlet phrase 引入了一个同名的新变量,有效地隐藏了函数其余部分的参数。它实际上并没有改变原始名称中的值。

关于rust - 影子变量在 Rust 中不起作用,给出生命周期错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71183065/

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