“ single_use_lifetimes”在具有派生函数的结构上是什么意思,以及如何解决它?

时间:2018-08-27 16:13:19

标签: rust

#![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> {
  |                ^^
  |

playground

此警告是什么意思?该如何解决?

当忽略派生或函数时,不会显示此警告。

1 个答案:

答案 0 :(得分:5)

目的是防止类似这样的代码,在这些代码中,生命周期没有必要明确指定:

const A &reward = (score > 5) ? foo1() : foo2();

相反,最好使用pub fn example<'a>(_val: SomeType<'a>) {}

'_

如果您expand your code并将其修整,则会得到以下信息:

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> ...

  

如何解决?

我不知道它是否可以不重写'_的{​​{1}}实现。

另请参阅: