gpt4 book ai didi

rust - 为什么 Rust 调试特性的实现使用 Formatter<'_> 类型省略

转载 作者:行者123 更新时间:2023-12-03 11:25:53 26 4
gpt4 key购买 nike

很久以前我就有这个问题,从我开始学习 Rust 的第一天起。我了解到 std::fmt::Debug 的实现有函数签名fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result .
起初我只是复制这个签名并将其视为标准样板代码。然而,随着我了解的更多,我意识到 <'_>意味着终生省略。我做了一些研究,根据 issue #49469 <'_>可以让返回值根据参数推断其生命周期(这真的很酷)。但我也看到有人使用 <'_>广泛与 fmt::Formatter ,例如 standard library documentmio ,在这些情况下 <'_>不应更改默认的生命周期推断行为。另外,我用下面的代码做了一个快速测试

use std::fmt;

struct Test();

impl fmt::Debug for Test {
fn fmt(&self,fmt:&mut fmt::Formatter) -> fmt::Result {
write!(fmt,"test")?;
Ok(())
}
}

fn main() {
let t = Test();
println!("{:?}",t);
}
它编译并运行。 <'_>也是如此这里有一些我不知道的边缘情况的特殊用法?
提前致谢。

最佳答案

来自 Rust RFC 2115: Argument Lifetimes :

You can write '_ to explicitly elide a lifetime, and it is deprecated to entirely leave off lifetime arguments for non-& types.


从包含的动机来看:

[A] point of confusion for newcomers and old hands alike is the fact that you can leave off lifetime parameters for types:

struct Iter<'a> { ... }

impl SomeType {
// Iter here implicitly takes the lifetime from &self
fn iter(&self) -> Iter { ... }

As detailed in the ergonomics initiative blog post, this bit of lifetime elision is considered a mistake: it makes it difficult to see at a glance that borrowing is occurring, especially if you're unfamiliar with the types involved. (The & types, by contrast, are universally known to involve borrowing.)


总之,你应该使用 fmt::Formatter<'_> .

关于rust - 为什么 Rust 调试特性的实现使用 Formatter<'_> 类型省略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63314288/

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