gpt4 book ai didi

rust - 是否可以禁用 Rust 的生命周期省略?

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

是否可以在每个文件的基础上禁用 Rust 的生命周期省略,也许使用 #[attribute]

我正在学习生命周期,我认为这可能会有所帮助。

最佳答案

Is it possible to disable Rust's lifetime elision on a per-file basis

没有。

我能提供的最佳替代方案是请求与 needless_lifetimes 相对的 Clippy 功能然后启用它。我不知道这样的请求是否会被其他人想要。

与此同时,您可以启用该 lint 并手动确保它为每个函数触发。


供引用,there are only 3 rules :

Lifetimes on function or method parameters are called input lifetimes, and lifetimes on return values are called output lifetimes.

The compiler uses three rules to figure out what lifetimes references have when there aren’t explicit annotations. The first rule applies to input lifetimes, and the second and third rules apply to output lifetimes. If the compiler gets to the end of the three rules and there are still references for which it can’t figure out lifetimes, the compiler will stop with an error. These rules apply to fn definitions as well as impl blocks.

The first rule is that each parameter that is a reference gets its own lifetime parameter. In other words, a function with one parameter gets one lifetime parameter: fn foo<'a>(x: &'a i32); a function with two parameters gets two separate lifetime parameters: fn foo<'a, 'b>(x: &'a i32, y: &'b i32); and so on.

The second rule is if there is exactly one input lifetime parameter, that lifetime is assigned to all output lifetime parameters: fn foo<'a>(x: &'a i32) -> &'a i32.

The third rule is if there are multiple input lifetime parameters, but one of them is &self or &mut self because this is a method, the lifetime of self is assigned to all output lifetime parameters. This third rule makes methods much nicer to read and write because fewer symbols are necessary.


就其值(value)而言,在 Rust 1.0 之前,这 3 个生命周期省略规则并不存在,只有第一个。然而,标准库中使用引用的所有函数和方法中大约 87% 都包含在 3 个省略规则中,这就是它们被采用的原因。生命周期省略是常见的情况。

关于rust - 是否可以禁用 Rust 的生命周期省略?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41250915/

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