Why doesn't this life-related connection cause an error?

This code compiles and works, but in my opinion, it should not compile:

use std::fmt::Display; pub fn test<S>(s: S) where S: Display + 'static, { println!("test: {}", s); } fn main() { let s = String::from("string"); test(s); } 

The lifetime of the s variable is in main , but the test function has a border that s must be 'static . I think the lifetime of the variable s should be 'static or longer than 'static . What is wrong with my reasoning?

+7
rust
source share
1 answer

A score of S: 'a means that any references contained in S must reside at least as long as 'a . For S: 'static this means that references to S must have a lifetime of 'static . The String type does not contain references (owns its data), and therefore compilation of code.

Quote book :

Types without references are considered T: 'static . Since 'static means that the link should work as long as the entire program, a type that does not contain links, meets the criteria of all links that live up to the full program (since there are no links).

If instead of the test(&s) function, you call the function :

 error[E0597]: `s` does not live long enough --> src/main.rs:14:11 | 14 | test(&s); | ^ does not live long enough 15 | } | - borrowed value only lives until here | = note: borrowed value must be valid for the static lifetime... 

Here S is &'a String for some lifetime 'a , and to bind the lifetime requires 'a must be 'static , which is not so.

+11
source share

All Articles