暗黙の境界
ライフタイム境界はしばしば型を妥当にするよう推論される。
fn requires_t_outlives_a<'a, T>(x: &'a T) {}
型
&'a T
が妥当であるには、型パラメタT
は'a
より長生きである事が要求される。これが推論されるのは、関数のシグネチャが型&'a T
を含んで、それがT: 'a
が守られると妥当になるためである。暗黙の境界は全ての関数のパラメタと出力のために追加される。
requires_t_outlives_a
の内側ではT: 'a
が守られると仮定でき、明示的にそれを指定しなくてもよい:fn requires_t_outlives_a_not_implied<'a, T: 'a>() {} fn requires_t_outlives_a<'a, T>(x: &'a T) { // This compiles, because `T: 'a` is implied by // the reference type `&'a T`. requires_t_outlives_a_not_implied::<'a, T>(); }
fn not_implied<'a, T>() { // This errors, because `T: 'a` is not implied by // the function signature. requires_t_outlives_a_not_implied::<'a, T>(); }
ライフタイム境界のみが暗示され、トレイト境界はまだ明示的に追加しなければならない。以下の例はそのためエラーになる:
use std::fmt::Debug; struct IsDebug<T: Debug>(T); // error[E0277]: `T` doesn't implement `Debug` fn doesnt_specify_t_debug<T>(x: IsDebug<T>) {}
ライフタイム境界は任意の型における型の定義や impl ブロックにおいても推論される:
struct Struct<'a, T> { // This requires `T: 'a` to be well-formed // which is inferred by the compiler. field: &'a T, } enum Enum<'a, T> { // This requires `T: 'a` to be well-formed, // which is inferred by the compiler. // // Note that `T: 'a` is required even when only // using `Enum::OtherVariant`. SomeVariant(&'a T), OtherVariant, } trait Trait<'a, T: 'a> {} // This would error because `T: 'a` is not implied by any type // in the impl header. // impl<'a, T> Trait<'a, T> for () {} // This compiles as `T: 'a` is implied by the self type `&'a T`. impl<'a, T> Trait<'a, T> for &'a T {}