rust - 为什么此生命周期绑定(bind)不会导致错误?

标签 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);
}

变量 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/

相关文章:

rust - 如何将 C 可变长度数组代码转换为 Rust?

rust - 如何让 Racer 与 Atom 一起工作?

rust - 如何将不相交的切片从向量传递到不同的线程?

返回指向局部变量的指针时的堆栈行为

rust - 如何为参数化特征实现特征

特征作为函数的返回值

return - 为什么提早归还未完成未偿还的借贷?

generics - 如何提供使用通用impl的适当类型?

rust - 在 Rust 中,如何限制泛型 T 以允许模数?

rust - 在 Rust 中使用本地可变副本迭代数组