2

Why does this rust code compile?

use std::fmt::Display;

fn g<T: 'static + Display>(t: T) {
    println!("{}", t);
}

fn t() {
    let x: i32 = 12;
    g(x);
}

fn main() {
    t();
}

Certainly in the function t() the local variable x is not static, yet the template specification of g seems to the demand that it must be. What am I misunderstanding?

For context: the example above is clearly very contrived. In a more complicated setting that I am working on, the compiler is forcing me to use T: 'static instead of just T, but I don't want to use it just for static types. To my surprise however it just also works for non static variables and I am confused...

Slugger
  • 665
  • 1
  • 5
  • 17
  • 3
    The bound `T: 'static` means that `T` only holds references that outlive the `'static` lifetime, not that `T` has to be a `static` item. And because `i32` holds no references at all, this is trivially true. – isaactfa Jun 13 '23 at 21:43
  • @isaactfa Thanks for the answer, that clears it up. Feel free to post as an answer and I will accept if you are interested in fake internet points :) – Slugger Jun 13 '23 at 21:48
  • 6
    See [Common Rust Lifetime Misconceptions](https://github.com/pretzelhammer/rust-blog/blob/master/posts/common-rust-lifetime-misconceptions.md#2-if-t-static-then-t-must-be-valid-for-the-entire-program) for more. – kmdreko Jun 13 '23 at 21:49
  • Thanks you @kmdreko – Slugger Jun 13 '23 at 21:51

1 Answers1

3

The bound T: 'static means that T only holds references that outlive the 'static lifetime (or more generally, all lifetime parameters on T do), not that T has to be a static item. And because i32 holds no references at all, this is trivially true. For reference, see the Rust reference and this handy guide, suggested by kmdreko.

isaactfa
  • 5,461
  • 1
  • 10
  • 24