问题描述
如果我有两个功能
// implicit
fn foo(x: &i32) {
}
// explicit
fn bar<'a>(x: &'a i32) {
}
什么时候foo
返回错误并且bar
是正确的函数头?我对为什么会明确声明生命周期感到困惑:
When would foo
return an error and bar
be the correct function header? I'm confused as to why I would explicitly declare a lifetime:
我了解生命周期是什么,但是为我明确指定生命周期'a
做什么是什么?作为参考,我使用锈皮书作为阅读材料
I understand what a lifetime is, but what does explicitly specifying a lifetime 'a
do for me? For reference I'm using the Rust book as reading material
推荐答案
实际上,必须编写生命周期注释的#1原因是,因为编译器会要求您.它将拒绝终身淘汰规则未涵盖的功能签名. >.
Practically speaking, the #1 reason you'll have to write lifetime annotations is because the compiler asks you so. It will reject function signatures which are not covered by lifetime elision rules.
我假设您想要一个简单的示例,其中必须使用生命周期.想象以下情况:
I assume you would like an simple example where lifetimes are mandatory. Imagine the following scenario:
struct Blah<'a> {
hoy: &'a u8
}
fn want_a_hoy(blah: &Blah) -> &u8 {
blah.hoy
}
意图很明显,但是编译器无法处理它:
The intention is obvious, but the compiler doesn't handle it:
<anon>:7:35: 7:38 error: missing lifetime specifier [E0106]
<anon>:7 fn want_a_hoy(blah: &Blah) -> &u8 {
^~~
<anon>:7:35: 7:38 help: see the detailed explanation for E0106
<anon>:7:35: 7:38 help: this function's return type contains a borrowed value, but
the signature does not say which one of `blah`'s 2 elided
lifetimes it is borrowed from
在这种情况下,注释可以解决问题:
In this case, annotations solve the problem:
fn want_a_hoy<'a, 'b>(blah: &'b Blah<'a>) -> &'a u8 {
blah.hoy
}
在这里您两次指定'a
(在Blah<'a>
和&'a
上).这是一辈子!因此,您在这里对编译器说的是:此函数对包含内部引用的blah进行引用.我将返回与该blah的内部引用一样长的生命."在这种情况下,签名强烈地暗示了您很可能会返回来自blah内幕的东西.
Here you're specifying 'a
twice (on Blah<'a>
and &'a
). This is the same lifetime! So what you're saying to the compiler here is: "This function takes a reference to a blah containing an inner reference. I will return something which lives exactly as long as the inner reference of the blah." In this case, the signature gives a strong hint that you're likely to return something coming from the innards of the blah.
这篇关于什么时候需要在Rust中指定显式生存期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!