请考虑下面的例子
struct Foo {
val: &str
}
fn main() {
let hello = String::from("hello");
let foo = Foo{ val: &hello[..]};
}
这不能编译,因为需要一个生命周期.一个非常简单的解决方法如下:
struct Foo<'a> {
val: &'a str
}
为什么编译器不能假设(作为合理的默认设置)引用将与 struct Foo
一样长?有没有不会出现这种情况的用例?