Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How/why is the rust compiler here ignoring that a template argument should have static lifetime?

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…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading