边界
就像泛型类型可以有边界一样,生命周期(本身也是泛型的)也使用边界。这里的 :
字符的含义略有不同,但 +
的含义相同。注意以下内容的解读
T: 'a
:T
中的所有引用都必须比生命周期'a
长寿。T: Trait + 'a
:类型T
必须实现 traitTrait
并且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 // some lifetime `'a` unknown by `Ref`. `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); }