首页 > 解决方案 > `single_use_lifetimes` 在函数中派生的结构上意味着什么以及如何解决它?

问题描述

#![warn(single_use_lifetimes)]

fn do_foo() {
    #[derive(Debug)]
    struct Foo<'a> {
        bar: &'a u32,
    }
}

导致此警告:

warning: lifetime parameter `'a` only used once
 --> src/lib.rs:6:16
  |
6 |     struct Foo<'a> {
  |                ^^
  |

操场

这个警告是什么意思?如何解决?

省略派生或函数时不会显示此警告。

标签: rust

解决方案


目的是防止这样的代码,其中生命周期是没有意义的明确指定:

pub fn example<'a>(_val: SomeType<'a>) {}

相反,最好使用'_

pub fn example(_val: SomeType<'_>) {}

如果你扩展你的代码并把它修剪下来,你会得到:

use std::fmt;

struct Foo<'a> {
    bar: &'a u32,
}

impl<'a> fmt::Debug for Foo<'a> {
    fn fmt(&self, _f: &mut fmt::Formatter) -> fmt::Result { Ok(()) }
}
warning: lifetime parameter `'a` only used once
 --> src/lib.rs:9:6
  |
9 | impl<'a> fmt::Debug for Foo<'a> {
  |      ^^
  |

也就是说,<'a>不需要,但派生无论如何都会添加它(因为自动生成代码很困难)。

老实说,我不知道这里的代码会发生什么变化,因为你不能'_在那里使用结构的通用生命周期......

如何解决?

我不知道它是否可以,无需重写derive.Debug

也可以看看:


推荐阅读