<'a,'b:'a>意味着生存期'b必须超过生存期'a? [英] Does <'a, 'b: 'a> mean that the lifetime 'b must outlive the lifetime 'a?

查看:86
本文介绍了<'a,'b:'a>意味着生存期'b必须超过生存期'a?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现一个类似于调试 builders 由标准库定义.它们是使用如下结构定义的:

I want to implement a builder similar to the debug builders defined by the standard library. They are defined using structures like the following:

struct DebugFoo<'a, 'b: 'a> {
    fmt: &'a mut std::fmt::Formatter<'b>
}

由于我不了解<'a, 'b: 'a>的含义,也无法在Rust的书或Rust的参考文献中找到它(至少与生命周期有关),所以我只是尝试删除不了解的内容会发生什么:

Since I don't understand what the form <'a, 'b: 'a> means nor I can find it mentioned in the Rust book or the Rust reference (at least concerning lifetimes), I just tried to remove what I don't understand to see what happens:

struct DebugFoo<'a, 'b> {
    fmt: &'a mut std::fmt::Formatter<'b>
}

编译它,我得到这个错误:

Compiling it I get this error:

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寿命长,并抛出错误.

It makes sense to me: 'a and 'b are different lifetimes so, to be on the safe side, Rust (the borrow checker?) assumes that 'a will outlive 'b, and throws the error.

现在,我可以猜测<'a, 'b: 'a>表示生存期'b必须长于生存期'a.我猜对了吗?还是还有更多?我如何找到它的记录文件?

Now I can guess that <'a, 'b: 'a> means that the lifetime 'b must be longer than the lifetime 'a. I've guessed right? Or there is more? How can I find it documented?

推荐答案

冒号被读取为有效期",因此

The colon is read "outlives", so

'long: 'short

读为"'long寿命长于'short".

至于有关该主题的官方文档,到目前为止,我唯一看到的文档记录在RFC关于生命周期的限制.

As for an official doc on the topic, the only place I've seen it documented so far is in the RFC on lifetime bounds.

这篇关于&lt;'a,'b:'a&gt;意味着生存期'b必须超过生存期'a?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆