边界
就像泛型类型可以被边界约束一样,生命周期(本身也是泛型)也使用边界。:
字符在这里的含义略有不同,但 +
的含义相同。请注意以下内容的解读方式
T: 'a
:T
中的*所有*引用必须比生命周期'a
更长。T: Trait + 'a
:类型T
必须实现特征Trait
,并且T
中的*所有*引用必须比'a
更长。
下面的示例展示了在关键字 where
之后使用的上述语法
use std::fmt::Debug; // Trait to bound with. #[derive(Debug)] struct Ref<'a, T: 'a>(&'a T); // `Ref` contains a reference to a generic type `T` that has // an unknown lifetime `'a`. `T` is bounded such that any // *references* in `T` must outlive `'a`. Additionally, the lifetime // of `Ref` may not exceed `'a`. // A generic function which prints using the `Debug` trait. fn print<T>(t: T) where T: Debug { println!("`print`: t is {:?}", t); } // Here a reference to `T` is taken where `T` implements // `Debug` and all *references* in `T` outlive `'a`. In // addition, `'a` must outlive the function. fn print_ref<'a, T>(t: &'a T) where T: Debug + 'a { println!("`print_ref`: t is {:?}", t); } fn main() { let x = 7; let ref_x = Ref(&x); print_ref(&ref_x); print(ref_x); }