我想实现一个类似于标准库定义的调试builders的构建器。它们使用如下结构定义:
struct DebugFoo<'a, 'b: 'a> {
fmt: &'a mut std::fmt::Formatter<'b>
}
由于我不明白<'a, 'b: 'a>
形式的含义,也无法在Rust书或Rust参考文献中找到它(至少关于生命期),我只是试图删除我不理解的内容看看会发生什么:
struct DebugFoo<'a, 'b> {
fmt: &'a mut std::fmt::Formatter<'b>
}
编译它我收到此错误:
in type `&'a mut core::fmt::Formatter<'b>`, reference has a longer
lifetime than the data it references
这个说明:
the pointer is valid for the lifetime 'a as defined on the struct at 1:0
but the referenced data is only valid for the lifetime 'b as defined on
the struct at 1:0
这对我来说很有意义:'a
和'b
是不同的生命周期,所以,为了安全起见,Rust(借用检查器?)假定'a
将超过{{} 1}},并抛出错误。
现在我可以猜测'b
表示生命周期<'a, 'b: 'a>
必须长于生命周期'b
。我猜对了吗?还是还有更多?我怎样才能找到它?
答案 0 :(得分:19)
冒号读作“outlives”,所以
id
的读数为“my_textview
超过'long: 'short
”。
至于关于该主题的官方文件,到目前为止,我所见到的唯一一个地方是Runtime Resource Overlay。
答案 1 :(得分:8)
是的,你是对的。
绑定<...: 'a>
表示...
(类型或其他生命周期)需要能够超过'a
。例如。 'b: 'a
表示&#34; 'b
必须至少与'a
&#34; (但不是严格过时:它们可以是相同的)。