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

구조체

struct 키워드를 사용하여 생성할 수 있는 구조체(“structs”)에는 세 가지 유형이 있습니다:

  • 기본적으로 이름이 붙은 튜플인 튜플 구조체.
  • 전통적인 C 구조체
  • 필드가 없는 유닛 구조체로, 제네릭에 유용합니다.
// 사용되지 않는 코드에 대한 경고를 숨기기 위한 속성입니다.
#![allow(dead_code)]

#[derive(Debug)]
struct Person {
    name: String,
    age: u8,
}

// 유닛 구조체
struct Unit;

// 튜플 구조체
struct Pair(i32, f32);

// 두 개의 필드를 가진 구조체
struct Point {
    x: f32,
    y: f32,
}

// 구조체는 다른 구조체의 필드로 재사용될 수 있습니다.
struct Rectangle {
    // 사각형은 공간상에서 왼쪽 위와 오른쪽 아래 모서리의 위치로 지정될 수 있습니다.
    top_left: Point,
    bottom_right: Point,
}

fn main() {
    // 필드 초기화 축약형(field init shorthand)으로 구조체를 생성합니다.
    let name = String::from("피터");
    let age = 27;
    let peter = Person { name, age };

    // 디버그용 구조체 출력
    println!("{:?}", peter);

    // `Point` 인스턴스 생성
    let point: Point = Point { x: 5.2, y: 0.4 };
    let another_point: Point = Point { x: 10.3, y: 0.2 };

    // 좌표의 필드에 접근
    println!("좌표 좌표: ({}, {})", point.x, point.y);

    // 구조체 업데이트 구문을 사용하여 다른 포인트의 필드를 활용해
    // 새로운 포인트를 만듭니다.
    let bottom_right = Point { x: 10.3, ..another_point };

    // `another_point`의 필드를 사용했으므로 `bottom_right.y`는 `another_point.y`와 동일합니다.
    println!("두 번째 좌표: ({}, {})", bottom_right.x, bottom_right.y);

    // `let` 바인딩을 사용하여 좌표를 구조 분해합니다.
    let Point { x: left_edge, y: top_edge } = point;

    let _rectangle = Rectangle {
        // 구조체 인스턴스 생성은 표현식이기도 합니다.
        top_left: Point { x: left_edge, y: top_edge },
        bottom_right: bottom_right,
    };

    // 유닛 구조체 인스턴스 생성
    let _unit = Unit;

    // 튜플 구조체 인스턴스 생성
    let pair = Pair(1, 0.1);

    // 튜플 구조체의 필드에 접근
    println!("페어는 {:?}와 {:?}를 포함합니다", pair.0, pair.1);

    // 튜플 구조체 구조 분해
    let Pair(integer, decimal) = pair;

    println!("페어는 {:?}와 {:?}를 포함합니다", integer, decimal);
}

실습

  1. Rectangle의 넓이를 계산하는 rect_area 함수를 추가하세요. (중첩된 구조 분해를 사용해 보세요).
  2. Pointf32를 인자로 받아, 해당 포인트를 왼쪽 위 모서리로 하고 f32에 해당하는 너비와 높이를 가진 Rectangle을 반환하는 square 함수를 추가하세요.

참고

속성, raw 식별자구조 분해