Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rust function does not have static lifetime?

Tags:

People also ask

What is the static lifetime Rust?

As a reference lifetime 'static indicates that the data pointed to by the reference lives for the entire lifetime of the running program.

Does Rust have static variables?

In Rust global variables are declared with the static keyword. In C there is a difference between static variables (with translation unit scope) and non-static global variables (with truly global scope).

What is a static string in Rust?

7 months ago. by John Otieno. A static variable refers to a type of variable that has a fixed memory location. They are similar to constant variables except they represent a memory location in the program.


I am trying to make this simple code compile:

fn dox(x: u8) -> u8 { x*2 }

fn main() {
    let cb: &'static (Fn(u8) -> u8) = &dox;
}

But it fails with Rust 1.9:

x.rs:4:40: 4:43 error: borrowed value does not live long enough
x.rs:4     let cb: &'static (Fn(u8) -> u8) = &dox;
                                              ^~~
note: reference must be valid for the static lifetime...
x.rs:4:44: 5:2 note: ...but borrowed value is only valid for the block suffix following statement 0 at 4:43
x.rs:4     let cb: &'static (Fn(u8) -> u8) = &dox;
x.rs:5 }
error: aborting due to previous error

How is it possible that a free function does not have static lifetime? How could this code be unsafe?