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

4

从我开始学习rust的第一天起,我就一直有这个问题。我了解到std::fmt::Debug的实现具有以下函数签名:

fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result

起初,我只是复制这个签名,并将其视为标准的样板代码。然而,随着我的学习深入,我意识到<'_>表示生命周期省略。我进行了一些研究,根据issue#49469<'_>可以使返回值根据参数来推断它的生命期(这真的很酷)。但是,我也看到人们在fmt::Formatter中广泛使用<'_>,例如标准库文档mio,在这些情况下,<'_>不应更改默认的生命周期推断行为。此外,我使用以下代码进行了快速测试:

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);
}

它可以编译和运行。那么在这里使用的 <'_> 是否具有一些我不知道的特殊用途或边缘情况呢?
提前致谢。
1个回答

5

来自Rust RFC 2115:生命周期参数:

您可以使用'_表示显式省略生命周期,对于非&类型完全省略生命周期参数已被弃用。

并且在其动机中提到:

[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<'_>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接