3.1 Structures
세 타입의 구조체를 struct
키워드를 사용해서 생성할 수 있다.
- 일반적으로 튜플(집합)이라 이름 지어진 집합 구조체
- 전통적인 C 구조체들
- 필드를 갖지 않는 단위 구조체, 제네릭에 유용하다.
// 유닛 구조체
struct Nil;
// 튜플 구조체
struct Pair(i32, f32);
// 두 필드를 갖는 구조체
struct Point {
x: f32,
y: f32,
}
// 구조체는 다른 구조체의 필드로 사용될 수 있다.
#[allow(dead_code)]
struct Rectangle {
p1: Point,
p2: Point,
}
fn main() {
// `Point` 초기화;
let point: Point = Point { x: 0.3, y: 0.4 };
// 포인트의 필드에 접근하는 방식.
println!("point coordinates: ({}, {})", point.x, point.y);
// `let` 바인딩을 통해 재구조화.
let Point { x: my_x, y: my_y } = point;
let _rectangle = Rectangle {
// 구조체 초기화는 표현문이기도 하다.
p1: Point { x: my_y, y: my_x },
p2: point,
};
// 단위 구조체 초기화
let _nil = Nil;
// 튜플 구조체 초기화
let pair = Pair(1, 0.1);
// 튜플 구조체에 접근하는 방식.
println!("pair contains {:?} and {:?}", pair.0, pair.1);
// 튜플 구조체의 재구조화
let Pair(integer, decimal) = pair;
println!("pair contains {:?} and {:?}", integer, decimal);
}
Activity
rect_area
함수를 추가하여 직사각형의 면적을 계산해보자. (중첩 역구조화를 시도해보자.)square
함수를 추가하는데Point
와f32
를 인자로 받게 하고,Rectangle
을 반환할 때 가장 낮은 왼쪽 코너 point와 폭과 넓이는f32
로 해라.Add a function
rect_area
which calculates the area of a rectangle (try using nested destructuring).- Add a function
square
which takes aPoint
and af32
as arguments, and returns aRectangle
with its lower left corner on the point, and a width and height corresponding to thef32
.