这段代码可以编译并工作,但根据我的理解,它不应该编译:
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);
}
变量 s
的生命周期在 main
中,但是函数 test
有一个 S
必须的界限是'静态的
。我认为变量 s
的生命周期必须是 'static
或大于 'static
。我的推理有什么问题?
最佳答案
绑定(bind) S: 'a
意味着 S
中包含的任何引用必须至少与 'a
一样长。对于 S: 'static
,这意味着 S 中的引用必须具有 'static
生命周期。 String
类型不包含任何引用(它拥有自己的数据),因此代码可以编译。
引用 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).
如果您使用 test(&s)
调用该函数,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...
这里,S
是 &'a String
某个生命周期 'a
,生命周期绑定(bind)要求 'a
必须是 'static
,但事实并非如此。
关于rust - 为什么此生命周期绑定(bind)不会导致错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47638702/