我想实现一个类似于标准库定义的调试构建器的构建器.它们使用如下结构定义:
struct DebugFoo<'a, 'b: 'a> {
fmt: &'a mut std::fmt::Formatter<'b>
}
Run Code Online (Sandbox Code Playgroud)
既然我不明白表格的<'a, 'b: 'a>含义,也不能在Rust书或Rust参考文献中找到它(至少关于生命周期),我只是试图删除我不明白的内容,看看会发生什么:
struct DebugFoo<'a, 'b> {
fmt: &'a mut std::fmt::Formatter<'b>
}
Run Code Online (Sandbox Code Playgroud)
编译它我得到这个错误:
in type `&'a mut core::fmt::Formatter<'b>`, reference has a longer
lifetime than the data it references
Run Code Online (Sandbox Code Playgroud)
而且这个说明:
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
Run Code Online (Sandbox Code Playgroud)
这对我来说是有道理的:'a并且'b是不同的生命周期,所以,为了安全起见,Rust(借用检查器?)假定它'a会比生命更长'b,并抛出错误.
现在我可以猜测这<'a, 'b: 'a>意味着寿命'b必须长于寿命'a.我猜对了吗?还是还有更多?我怎样才能找到它?
mdu*_*dup 20
冒号读作"outlives",所以
'long: 'short
Run Code Online (Sandbox Code Playgroud)
读为" 'longoutlives 'short".
至于关于该主题的官方文档,到目前为止我唯一记录的地方是关于生命界限的RFC.
是的,你是对的.
绑定<...: 'a>意味着...(一种类型或另一种生命周期)需要能够活得更久'a.例如,'b: 'a意味着" 'b必须至少生活'a"(尽管不是严格的生命:它们可以是相同的).