gpt4 book ai didi

rust - 争论要求 _ 是为 'static 借用的 - 我该如何解决这个问题?

转载 作者:行者123 更新时间:2023-11-29 08:04:31 27 4
gpt4 key购买 nike

我无法理解 Rust 编译器的生命周期/借用错误。问题似乎是 Rust 假设当参数被传递给返回静态值引用的函数时,参数引用也必须是静态的。

#[derive(Debug)]
struct TestThingy<'a> {
label: &'a str,
}

const TEST_VALUES: [TestThingy; 3] = [
TestThingy { label: "one" },
TestThingy { label: "two" },
TestThingy { label: "three" },
];

pub fn value_for_num(num: &str) -> Option<&'static TestThingy> {
TEST_VALUES.iter().find(|value| value.label == num)
}

pub fn test_out_thingy() {
let tmp_val = String::from("two");
if let Some(test_thingy) = value_for_num(&tmp_val) {
println!("test_thingy: {:?}", test_thingy);
}
}

fn main() {
test_out_thingy();
}

Rust 错误:error[E0597]: `tmp_val` does not live long enough - E0597 指的是当一个值在它仍然被借用时被丢弃,这不会发生在这里 - 我不但我知道如何说服 Rust 相信这一点。

这段代码背后的想法,对于更多上下文,它是一种编译时/静态配置的查找机制(在我的代码库中,它们是 Syntax 值,根据提供的文件名 &str)。因此,提供的参数确实不会像静态配置一样存在,但我不明白为什么这是个问题。返回值不/不能包含参数作为引用,所以我非常不清楚为什么会发生这种借用错误。

最佳答案

问题出在value_for_num的函数签名上.

你表明你返回一个静态引用给一个TestThingy但没有说明 TestThingy<'x> 是哪种引用文献可能持有。因此,编译器假定未指定的输入引用生命周期可能与未指定的引用输出生命周期相关联 inside TestThingy .

即编译器看到这个:

pub fn value_for_num<'a>(num: &'a str) -> Option<&'static TestThingy<'a>>

如果您更改签名以指定包含的引用也是静态的,那么它会编译。

pub fn value_for_num(num: &str) -> Option<&'static TestThingy<'static>>

关于rust - 争论要求 _ 是为 'static 借用的 - 我该如何解决这个问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58436950/

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