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

구조체

구조체에서의 라이프타임 어노테이션도 함수와 비슷합니다:

// `i32`에 대한 참조를 보관하는 `Borrowed` 타입입니다.
// `i32`에 대한 참조는 `Borrowed`보다 오래 살아야 합니다.
#[derive(Debug)]
struct Borrowed<'a>(&'a i32);

// 마찬가지로, 여기의 두 참조는 이 구조체보다 오래 살아야 합니다.
#[derive(Debug)]
struct NamedBorrowed<'a> {
    x: &'a i32,
    y: &'a i32,
}

// `i32`이거나 이에 대한 참조인 열거형입니다.
#[derive(Debug)]
enum Either<'a> {
    Num(i32),
    Ref(&'a i32),
}

fn main() {
    let x = 18;
    let y = 15;

    let single = Borrowed(&x);
    let double = NamedBorrowed { x: &x, y: &y };
    let reference = Either::Ref(&x);
    let number    = Either::Num(y);

    println!("x는 {:?}에서 빌려졌습니다", single);
    println!("x와 y는 {:?}에서 빌려졌습니다", double);
    println!("x는 {:?}에서 빌려졌습니다", reference);
    println!("y는 {:?}에서 빌려지지 *않았습니다*", number);
}

참고:

struct