พื้นฐาน 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.
สิ่งที่คุณจะได้เรียนรู้
- Tuples and .0 .1
- Arrays with [T; N]
- Returning two values
scores: [i32; 5]
720
951
582
883
644
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.
ประเด็นสำคัญ
- An array's length is part of its type: [i32; 5].
- A tuple can mix types: (3, -2.5).
- 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ฝึกฝน
เปิดตัวอย่างในคอมไพเลอร์ออนไลน์ ลองเปลี่ยนค่าหรือเพิ่มบรรทัด แล้วทายผลลัพธ์ก่อนกดรัน จากนั้นลองทำให้โค้ดผิดโดยตั้งใจ แล้วอ่านข้อความจากคอมไพเลอร์
เรียนบทนี้จบแล้วใช่ไหม
ทำเครื่องหมายว่าเรียนแล้วเพื่อติดตามความคืบหน้า
ความคืบหน้าของคุณถูกบันทึกไว้ในเบราว์เซอร์นี้ เข้าสู่ระบบเพื่อเก็บไว้ใช้ได้ทุกอุปกรณ์
ฝึกด้วยโจทย์
ใช้สิ่งที่เรียนในบทนี้แก้ปัญหาจริง ทุกโจทย์รันในเบราว์เซอร์ พร้อมการทดสอบทันทีและรีวิวจาก AI
- หาค่าสูงสุดในอาเรย์ หาค่าที่มากที่สุดในลิสต์ ง่าย
- Min and Max Together Find the smallest and largest value in one pass. ง่าย