2
#![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.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Tim Diekmann
  • 7,755
  • 11
  • 41
  • 69
  • Seems pretty straightforward: it's warning you that the lifetime is used only once in the struct. – trent Aug 27 '18 at 16:17
  • Yeah, but how can this be solved? (Without removing the `#![warn(...)]`) – Tim Diekmann Aug 27 '18 at 16:19
  • 1
    @trentcl What is the purpose of the warning in this context? The lint is supposed to be for suggesting when unnamed `'_` lifetimes can be used instead, but that doesn't appear to be the case here. – Peter Hall Aug 27 '18 at 16:19
  • @Peter This looks like a bug given the accepted answer, but at first I thought that maybe it doesn't *have* a purpose in this context, in which case "just turn it off" would be the correct answer. Lots of warnings exist that shouldn't be turned on all the time – trent Aug 27 '18 at 19:08

1 Answers1

5

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:

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366