Skip to content

Instantly share code, notes, and snippets.

@emctoo
Last active October 5, 2022 15:38
Show Gist options
  • Save emctoo/3d31ef14184765a9b8cfcdf5832c0fbe to your computer and use it in GitHub Desktop.
Save emctoo/3d31ef14184765a9b8cfcdf5832c0fbe to your computer and use it in GitHub Desktop.
my rust resources

Static

lifetime 中的 'static

  • 'static 表示生命周期是整个程序。
  • const 和 static 中的 'static 可以省略掉
  • 'static 可以强制转化到更短的生命周期

trait bound 中的 'static

  • 字面上,type 没有任何非 static lifetime 的引用
  • 表示 receiver 可以一直持有这个 type 也没有问题,直到 receiver 自动 drop 掉他
  • 不是reference的,直接 moved 的,receiver 拥有了所有权,当然是没有问题
  • 传进来是 reference 的就需要是 'static 的 lifetime了
  • https://rustwiki.org/en/rust-by-example/scope/lifetime/static_lifetime.html
use std::fmt::Debug;

fn print_it( input: impl Debug + 'static ) {
    println!( "'static value passed in is: {:?}", input );
}

fn main() {
    // i is owned and contains no references, thus it's 'static:
    let i = 5;
    print_it(i);

    // oops, &i only has the lifetime defined by the scope of
    // main(), so it's not 'static:
    print_it(&i);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment