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

トレイト

トレイトメソッドにおけるライフタイムの注釈は、基本的に関数と同様です。 impl にもライフタイムの注釈を付けられることに注意してください。

// ライフタイム注釈を持つ構造体。
#[derive(Debug)]
struct Borrowed<'a> {
    x: &'a i32,
}

// impl にライフタイムを注釈する。
impl<'a> Default for Borrowed<'a> {
    fn default() -> Self {
        Self {
            x: &10,
        }
    }
}

fn main() {
    let b: Borrowed = Default::default();
    println!("b is {:?}", b);
}

関連項目:

trait