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);
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Activity

  1. rect_area 함수를 추가하여 직사각형의 면적을 계산해보자. (중첩 역구조화를 시도해보자.)
  2. square 함수를 추가하는데 Pointf32를 인자로 받게 하고, Rectangle을 반환할 때 가장 낮은 왼쪽 코너 point와 폭과 넓이는 f32로 해라.

  3. Add a function rect_area which calculates the area of a rectangle (try using nested destructuring).

  4. Add a function square which takes a Point and a f32 as arguments, and returns a Rectangle with its lower left corner on the point, and a width and height corresponding to the f32.

See also:

attributes and destructuring

results matching ""

    No results matching ""