我设法想出了三个场景,在我看来表面上是相同的,但行为不同,如果有人能向我澄清原因,我将不胜感激……
第一个场景不符合我的实际预期:
fn main() {
let data = get_data();
println!("{}", data);
}
fn get_data() -> &'static str {
let x: String = String::from("hello");
return x.as_str(); // always fails with ownership issue
}
不出所料失败:returns a reference to data owned by the current function
然而,考虑到上面的预期,接下来的两个问题让我感到困惑:
这是成功的:
fn get_data() -> &'static str { // requires `'static` lifetime
let x = std::path::Path::new("thing");
match x.to_str() {
None => "",
Some(s) => s,
}
}
我本以为s
是函数所拥有的,所以不能返回,但在本例中,添加&'static str
作为返回类型(否则编译器会不高兴)允许该操作.
更令人费解的是,以下代码可以工作(编译器很高兴),not是否需要'static
个生命周期:
use std::path::Path;
pub fn parent_of(caller_file: &str) -> &str { // `'static` not required ??
let caller_file_p: &Path = Path::new(caller_file);
match caller_file_p.parent() {
None => if caller_file.starts_with("/") { "/" } else { "." },
Some(p) => match p.to_str() {
None => {
eprintln!("Bad UTF-8 sequence specified : '{}'", caller_file);
std::process::exit(100);
},
Some(s) => s,
}
}
}
我相信每个场景的细微差别都有一些有条不紊的解释,但我搞不懂.非常感谢您的澄清.