【发布时间】:2015-08-26 09:32:09
【问题描述】:
我想实现一个类似于标准库定义的调试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 长。我猜对了?或者还有更多?我怎样才能找到它的文档?
【问题讨论】: