Rust 'static trait bound

337 阅读1分钟

按照Rust中文档解释:

As a trait bound, it means the type does not contain any non-static references. Eg. the receiver can hold on to the type for as long as they want and it will never become invalid until they drop it.

由'static 限定的类型不能包含非static的引用类型。这确保接收者在生命周期内可以访问此类型,而不必担心此类型包含的引用被释放。

use std::fmt::Debug;

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


fn print_ref<T: Debug + 'static>(input: &T) { 
    println!( "'static value passed in is: {:?}", input ); 
}

fn use_it()
{
    // i is owned and contains no references, thus it's 'static:
    let i = 5;
    print_it(i);
    
    // success
    const S:i8 = 10;
    print_it(S);

    // success
    static S1:i8 = 11;
    print_it(S1);

    // failure
    // oops, &i only has the lifetime defined by the scope of
    // use_it(), so it's not 'static:
    print_it(&i);
    
    // success
    // 这段代码竟然不报错了!原因在于我们约束的是 `T`,但是使用的却是它的引用 `&T`
    print_ref(&i);
}