Rust cơ bản

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.

  • Cơ bản
  • Đọc trong 3 phút
  • 1 ví dụ chạy được
Bạn sẽ học được gì
  • 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.

Những điểm quan trọng

  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.

Ví dụ Rust chạy được

Rust
Chạy code →
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);
}
Lấy nút Run cho ví dụ này Kết quả khi chạy
first: 72, count: 5
lowest: 58, highest: 95
x = 3, y = -2.5

Luyện tập

Mở ví dụ trong trình biên dịch online, đổi một giá trị hoặc thêm một dòng, rồi đoán kết quả trước khi chạy. Sau đó cố ý làm code bị lỗi và đọc thông báo của trình biên dịch.

Bạn học xong bài này chưa?

Đánh dấu đã học để theo dõi tiến độ của bạn.

Tiếp theo: Vectors →

Luyện tập với thử thách

Áp dụng kiến thức của bài học này để giải một bài toán thực tế. Mỗi thử thách chạy ngay trên trình duyệt, có kiểm thử tức thì và AI nhận xét.

Tất cả thử thách