This code compiles and work, but according to my understanding, 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 variable s
is in main
, but the function test
has a bound that S
must be 'static
. I think the lifetime of variable s
must be 'static
or larger than 'static
. What's wrong with my reasoning?
The bound S: 'a
means that any references contained in S
must live at least as long as 'a
. For S: 'static
, this means that references in S must have a 'static
lifetime. The String
type doesn't hold any references (it owns its data), and therefore the code compiles.
Quoting the book:
Types without any references count as
T: 'static
. Because'static
means the reference must live as long as the entire program, a type that contains no references meets the criteria of all references living as long as the entire program (since there are no references).
If you call the function with test(&s)
instead, compilation will fail:
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 the lifetime bound requires that 'a
must be 'static
, which isn't the case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With