我有一个来自 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();
}
Run Code Online (Sandbox Code Playgroud)
Rust 错误:error[E0597]: `tmp_val` does not live long …
rust ×1