我遇到了section talking about lifetimes,一开始有点困惑。因此,我决定通过编写一些示例来尝试一下。 (Playground)
void limit_capabilities(void)
{
...
if (setuid(getuid()) < 0) {
perror("setuid");
exit(-1);
}
据我了解,fn main() {
let b = "hello";
let mut d = "Unassigned";
{
let a = "hi";
let c = lifetime(&a, &b);
d = &c;
}
// My confusion happens here, I was expecting a compile-time error
// since the lifetime of 'c' is the same as 'a' which is in the previous block
// from my understanding. But this compiles just fine
println!("{}", d);
}
fn lifetime<'a, 'b>(test: &'a str, test2: &'b str) -> &'a str {
println!("{}, {}", test, test2);
return "returned value of lifetime";
}
函数将生存期lifetime
绑定到返回的参考值。
因此,通常我希望行'a
在编译时中断,并出现一个错误,指出生存期println!("{}", d);
超出范围,这是我错的。
我理解错了什么? 为什么要编译此代码?
答案 0 :(得分:2)
找到上面评论中指出的关于contravariance的信息后,我写了这个小片段(类似于问题)
struct Potato(i32);
fn doesnt_work() {
let b = Potato(1);
let d;
{
let a = Potato(2);
let c = lifetime2(&b, &a);
d = c;
}
// Compile-time error ! Borrowed value does not live long enough.
println!("{}", d.0);
}
fn lifetime2<'a, 'b>(test: &'a Potato, test2: &'b Potato) -> &'a Potato {
return &Potato(test.0);
}
现在给出实际的预期编译时错误。
它在我最初的问题中发现生命周期被推断为'static
,这是str
引用中最常见的生命周期。