2.2 Tuples
튜플은 서로 다른 타입의 값들의 집합체이다. 튜플은 괄호 ()
를 사용해 생성되고, 각 튜플 자신은 타입 선언이 되어 있는 값(T1, T2, ...)으로 T1, T2는 그의 멤버의 타입이다. 함수가 튜플을 다양한 값을 반환할 때 사용할 수 있고, 튜플은 몇 개든 값을 보관할 수 있다.
// 튜플은 함수 인자로도 반환 값으로도 사용될 수 있다.
fn reverse(pair: (i32, bool)) -> (bool, i32) {
// `let`은 튜플의 멤버를 변수에 바인드 할 때 사용된다.
let (integer, boolean) = pair;
(boolean, integer)
}
// 다음 구조체는 activity 용.
#[derive(Debug)]
struct Matrix(f32, f32, f32, f32);
fn main() {
// 서로 다른 타입 무리의 튜플
let long_tuple = (1u8, 2u16, 3u32, 4u64,
-1i8, -2i16, -3i32, -4i64,
0.1f32, 0.2f64,
'a', true);
// tuple에서 색인으로 값을 추출 할 수 있다.
println!("long tuple first value: {}", long_tuple.0);
println!("long tuple second value: {}", long_tuple.1);
// 튜플이 튜플의 멤버가 될 수 있다.
let tuple_of_tuples = ((1u8, 2u16, 2u32), (4u64, -1i8), -2i16);
// 튜플은 출력 가능
println!("tuple of tuples: {:?}", tuple_of_tuples);
let pair = (1, true);
println!("pair is {:?}", pair);
println!("the reversed pair is {:?}", reverse(pair));
// 하나의 요소인 튜플을 만드려면, 괄호와는 별도로 쉼표를 통해 알리는게 필요하다.
println!("one element tuple: {:?}", (5u32,));
println!("just an integer: {:?}", (5u32));
// 튜플은 바인딩을 생성해서 역구조화 할 수 있다.
//tuples can be destructured to create bindings
let tuple = (1, "hello", 4.5, true);
let (a, b, c, d) = tuple;
println!("{:?}, {:?}, {:?}, {:?}", a, b, c, d);
let matrix = Matrix(1.1, 1.2, 2.1, 2.2);
println!("{:?}", matrix)
}
Activity
반복:
fmt::Display
trait을 상기 예제의 Matrix구조체
에 추가하여 디버그 형식{:?}
에서 표시 형식{}
로 변경했을 때, 다음과 같은 출력이 되도록 해보자:( 1.1 1.2 ) ( 2.1 2.2 )
print display 예제를 참고.
transpose
을reverse
함수를 뼈대로 추가하며 matrix를 인자로 허용해 두 요소가 교환된 matrix를 반환하도록 하자. 예:
println!("Matrix:\n{}", matrix);
println!("Transpose:\n{}", transpose(matrix));
결과는 다음과 같이 출력된다:
Matrix:
( 1.1 1.2 )
( 2.1 2.2 )
Transpose:
( 1.1 2.1 )
( 1.2 2.2 )