#![warn(single_use_lifetimes)]
fn do_foo() {
#[derive(Debug)]
struct Foo<'a> {
bar: &'a u32,
}
}
results in this warning:
warning: lifetime parameter `'a` only used once
--> src/lib.rs:6:16
|
6 | struct Foo<'a> {
| ^^
|
playground
What does this warning mean? How can this be solved?
This warning is not shown when omitting either the derive or the function.
The purpose is to prevent code like this, where the lifetime is meaningless to specify explicitly:
pub fn example<'a>(_val: SomeType<'a>) {}
Instead, it's preferred to use '_:
pub fn example(_val: SomeType<'_>) {}
If you expand your code and trim it down, you get this:
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> {
| ^^
|
That is, the <'a> isn't needed, but the derive adds it anyway (because automatically generating code is hard).
I honestly don't know what it would expect the code to change to here, as you can't use '_ for the struct's generic lifetimes there...
How can this be solved?
I don't know that it can, without rewriting the derive implementation of Debug.
See also:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With