境界

Just like generic types can be bounded, lifetimes (themselves generic) use bounds as well. The : character has a slightly different meaning here, but + is the same. Note how the following read:

  1. T: 'aT内の 全ての 参照は'aよりも長生きでなくてはなりません。
  2. T: Trait + 'a:上に加えてTTraitという名のトレイトを実装してなくてはなりません。

上記の構文を実際に動く例で見ていきましょう。whereキーワードの後に注目してください。

use std::fmt::Debug; // ライフタイムを紐付けるトレイト

#[derive(Debug)]
struct Ref<'a, T: 'a>(&'a T);
// `Ref`は`'a`というライフタイムを持つジェネリック型`T`に対する参照を持ち、
// `T`の値に対する *参照* は必ず`'a`よりも長生きでなくてはなりません。
// さらに、`Ref`のライフタイムは`'a`を超えてはなりません。

// `Debug`トレイトを利用して出力を行うジェネリック関数
fn print<T>(t: T) where
    T: Debug {
    println!("`print`: t is {:?}", t);
}

// `Debug`を実装している`T`への参照を取りません。`T`への *参照* は
// 必ず`'a`よりも長生きでなくてはなりません。さらに、`'a`は
// 関数自体よりも長生きでなくてはなりません。
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);
}

参照

generics, bounds in generics, and multiple bounds in generics