Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

rust

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

like image 641
Tim Diekmann Avatar asked Nov 15 '25 05:11

Tim Diekmann


1 Answers

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:

  • println!(), derive(Debug), derive(Clone), and probably many other macros break when using the elided_lifetimes_in_paths lint
like image 63
Shepmaster Avatar answered Nov 17 '25 20:11

Shepmaster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!