为什么这个生命周期绑定不会导致错误?

7

这段代码可以编译并且运行,但是根据我的理解它不应该能够编译:

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);
}
< p > 变量s的生命周期在main中,但函数test有一个绑定,要求S必须是'static'。我认为变量s的生命周期必须是'static'或大于'static'。我的推理有什么问题吗?< /p >
1个回答

11

绑定 S: 'a 意味着 S 中包含的任何引用必须至少与 'a 生命周期相同。对于 S: 'static,这意味着 S 中的引用必须具有 'static 生命周期。 String 类型不持有任何引用(它拥有自己的数据),因此代码编译通过。

引用 the book

没有任何引用的类型计为 T: 'static。因为 'static 表示引用必须与整个程序一样长寿,所以不包含引用的类型符合所有引用与整个程序同寿命的条件(因为没有引用)。

如果您使用 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&'a String,生命周期的限制要求'a必须是'static,但实际上并非如此。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接