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

省略

一部のライフタイムパターンは非常に一般的であるため、借用チェッカーは 入力の手間を省き、可読性を向上させるために、それらを省略することを許可します。 これは省略として知られています。Rust に省略が存在するのは、これらのパターンが 一般的であるという理由だけです。

次のコードは、省略の例をいくつか示しています。省略のより包括的な 説明については、本の ライフタイム省略 を参照してください。

// `elided_input` と `annotated_input` は本質的に同一のシグネチャを持ちます
// なぜなら、`elided_input` のライフタイムはコンパイラによって推論されるためです:
fn elided_input(x: &i32) {
    println!("`elided_input`: {}", x);
}

fn annotated_input<'a>(x: &'a i32) {
    println!("`annotated_input`: {}", x);
}

// 同様に、`elided_pass` と `annotated_pass` は同一のシグネチャを持ちます
// なぜなら、ライフタイムが `elided_pass` に暗黙的に追加されるためです:
fn elided_pass(x: &i32) -> &i32 { x }

fn annotated_pass<'a>(x: &'a i32) -> &'a i32 { x }

fn main() {
    let x = 3;

    elided_input(&x);
    annotated_input(&x);

    println!("`elided_pass`: {}", elided_pass(&x));
    println!("`annotated_pass`: {}", annotated_pass(&x));
}

関連項目:

省略