繁体   English   中英

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

[英]What does `single_use_lifetimes` mean on a struct with derive in a function and how to solve it?

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

操场

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

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

目的是防止这样的代码,因为生命周期没有必要明确指定:

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> ,但是无论如何派生类都会添加它(因为很难自动生成代码)。

老实说,我不知道代码会更改为此处,因为您不能在其中使用'_作为该结构的通用生命周期...

如何解决呢?

我不知道它是否可以不重写Debugderive实现。

也可以看看:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM