Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Межі

Так само, як узагальнені типи можуть мати межі, часи життя (самі по собі узагальнені) також використовують межі. Символ : тут має дещо інше значення, але + — той самий. Зверніть увагу, як слід читати таке:

  1. T: 'a: Усі посилання в T мають переживати час життя 'a.
  2. 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
// 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);
}

Дивіться також:

generics, bounds in generics, and multiple bounds in generics