gpt4 book ai didi

rust - 用一个撇号 (') 表示的标识符是什么?

转载 作者:行者123 更新时间:2023-11-29 07:40:04 25 4
gpt4 key购买 nike

我在 Rust 中遇到过许多用单个撇号表示的类型:

'static
'r
'a

撇号 (') 的意义是什么?也许它是引用的修饰符(&)?特定于引用的通用类型?我不知道这方面的文档藏在哪里。

最佳答案

这些是 Rust 的命名生命周期。

引自The Rust Programming Language :

Every reference in Rust has a lifetime, which is the scope for which that reference is valid. Most of the time lifetimes are implicit and inferred, just like most of the time types are inferred. Similarly to when we have to annotate types because multiple types are possible, there are cases where the lifetimes of references could be related in a few different ways, so Rust needs us to annotate the relationships using generic lifetime parameters so that it can make sure the actual references used at runtime will definitely be valid.

Lifetime annotations don’t change how long any of the references involved live. In the same way that functions can accept any type when the signature specifies a generic type parameter, functions can accept references with any lifetime when the signature specifies a generic lifetime parameter. What lifetime annotations do is relate the lifetimes of multiple references to each other.

Lifetime annotations have a slightly unusual syntax: the names of lifetime parameters must start with an apostrophe '. The names of lifetime parameters are usually all lowercase, and like generic types, their names are usually very short. 'a is the name most people use as a default. Lifetime parameter annotations go after the & of a reference, and a space separates the lifetime annotation from the reference’s type.

换句话说,生命周期近似于引用指向的数据有效的执行跨度。 Rust 编译器将保守地推断最短的生命周期可能是安全的。如果你想告诉编译器一个引用的生命周期比最短估计长,你可以给它命名,例如,输出引用与给定的输入引用具有相同的生命周期。

'static 生命周期是一个特殊的生命周期,是所有生命周期中最长的 - 在程序的持续时间内。一个典型的例子是在程序/模块的生命周期中始终可用的字符串“文字”。

您可以从this slide deck获得更多信息,从幻灯片 29 左右开始。

Lifetimes in Rust还深入讨论了生命周期。

关于rust - 用一个撇号 (') 表示的标识符是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22048673/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com