我在Rust编译器中犯了一个终生/borrow 错误,我无法理解.问题似乎是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指的是当一个值被删除,而它仍然被borrow ,这在这里没有发生-我不知道如何说服Rust.
这段代码背后的 idea 是,为了获得更多的上下文,它是编译时/静态配置的一种查找机制(在我的代码库中,它们是Syntax
个值,根据提供的文件名&str
进行匹配).因此,提供的参数实际上没有静态配置有效,但我不明白为什么这是一个问题.返回的值不包含参数作为引用,所以我非常不清楚为什么会发生这种borrow 错误.