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

jul*_*993 7 rust

这段代码编译和工作,但根据我的理解,它不应该编译:

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);
}
Run Code Online (Sandbox Code Playgroud)

变量的生命周期smain,但函数必须test有一个界限.我认为变量的生命周期必须大于或大于.我的推理有什么问题?S'statics'static'static

int*_*jay 11

绑定S: 'a意味着包含的任何引用S必须至少与之一致'a.对于S: 'static,这意味着S中的引用必须具有'static生命周期.该String类型不包含任何引用(它拥有其数据),因此代码编译.

引用这本书:

没有任何引用的类型计为T: 'static.因为'static意味着引用必须与整个程序一样长,所以不包含引用的类型符合所有引用的标准,只要整个程序生效(因为没有引用).

如果用test(&s)相反的方法调用函数,编译将失败:

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...
Run Code Online (Sandbox Code Playgroud)

在这里,S&'a String一段时间'a,并且生命期限必须是'a必须的'static,而事实并非如此.