我想实现一个类似于标准库定义的debug 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
将比'b
更长寿,并抛出错误。
现在我可以猜测
<'a, 'b: 'a>
意味着生命周期'b
一定比生命周期长'a
。我猜对了吗?或者还有更多?我怎样才能找到它的记录?
是的,你基本上是对的。
绑定
<...: 'a>
意味着 ...
(一种类型或另一种生命周期)需要能够比 'a
更长寿。例如。 'b: 'a
意味着“'b
的寿命必须至少与 'a
一样长”(但严格来说,并不是比寿命更长:它们可以相同)。
为了避免混淆(我最初对这个问题感到困惑),请注意,问题中的编译器错误在 Rust 中不再出现,因为在 2017 年,结构体上的 outlive 边界被推断出来(当需要字段格式良好时)。