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 Trait를 사용해야 합니다.

클로저를 반환하기 위해 유효한 트레이트들은 다음과 같습니다:

  • Fn
  • FnMut
  • FnOnce

이 외에도, 모든 캡처가 값에 의해 발생함을 나타내는 move 키워드를 반드시 사용해야 합니다. 이는 참조에 의한 캡처가 함수가 종료되는 즉시 드롭되어 클로저에 유효하지 않은 참조를 남기기 때문에 필요합니다.

fn create_fn() -> impl Fn() {
    let text = "Fn".to_owned();

    move || println!("이것은 {}입니다", text)
}

fn create_fnmut() -> impl FnMut() {
    let text = "FnMut".to_owned();

    move || println!("이것은 {}입니다", text)
}

fn create_fnonce() -> impl FnOnce() {
    let text = "FnOnce".to_owned();

    move || println!("이것은 {}입니다", text)
}

fn main() {
    let fn_plain = create_fn();
    let mut fn_mut = create_fnmut();
    let fn_once = create_fnonce();

    fn_plain();
    fn_mut();
    fn_once();
}

참고:

Fn, FnMut, 제네릭impl Trait.