Rust 기초

Rust Tuples and Arrays

Group a few values of different types in a tuple, and a fixed number of same-typed values in an array.

  • 초급
  • 3분 분량
  • 실행 가능한 예제 1개
배울 내용
  • Tuples and .0 .1
  • Arrays with [T; N]
  • Returning two values
scores: [i32; 5]
720
951
582
883
644
Indexes start at 0. The highest score is at index 1.

Fixed-size groups of values

A tuple groups a few values that can have different types. An array holds a fixed number of values of one type, and its length is part of its type.

[i32; 5] is an array of five i32 values. min_max returns two results at once as a tuple, and let (lowest, highest) unpacks them. Tuple fields are read by position with .0 and .1.

핵심 포인트

  1. An array's length is part of its type: [i32; 5].
  2. A tuple can mix types: (3, -2.5).
  3. let (a, b) = pair; unpacks a tuple.

실행 가능한 Rust 예제

Rust
코드 실행 →
main.rs
fn min_max(values: [i32; 5]) -> (i32, i32) {
    let mut min = values[0];
    let mut max = values[0];
    for value in values {
        if value < min {
            min = value;
        }
        if value > max {
            max = value;
        }
    }
    (min, max)
}

fn main() {
    let scores = [72, 95, 58, 88, 64];
    let (lowest, highest) = min_max(scores);

    println!("first: {}, count: {}", scores[0], scores.len());
    println!("lowest: {lowest}, highest: {highest}");

    let point = (3, -2.5);
    println!("x = {}, y = {}", point.0, point.1);
}
이 예제의 실행 버튼 만들기 코드 실행 결과
first: 72, count: 5
lowest: 58, highest: 95
x = 3, y = -2.5

연습

예제를 온라인 컴파일러에서 열고 값을 바꾸거나 한 줄을 추가한 다음, 실행하기 전에 출력을 예상해 보세요. 그런 다음 일부러 코드를 망가뜨리고 컴파일러 메시지를 읽어 보세요.

이 레슨을 마쳤나요?

학습 완료로 표시하면 진행 상황을 기록할 수 있습니다.

다음: Vectors →

챌린지로 연습하기

이 레슨에서 배운 내용으로 실제 문제를 풀어 보세요. 모든 챌린지는 브라우저에서 실행되며 즉시 테스트와 AI 리뷰를 받을 수 있습니다.

모든 챌린지