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);
}
इस उदाहरण के लिए Run बटन बनाएँ कोड चलाने का परिणाम
first: 72, count: 5
lowest: 58, highest: 95
x = 3, y = -2.5

अभ्यास

उदाहरण को ऑनलाइन कंपाइलर में खोलें, कोई मान बदलें या एक पंक्ति जोड़ें, और चलाने से पहले आउटपुट का अनुमान लगाएँ। फिर कोड में जान-बूझकर गलती करें और कंपाइलर का संदेश पढ़ें।

यह पाठ पूरा कर लिया?

अपनी प्रगति ट्रैक करने के लिए इसे सीखा हुआ मार्क करें।

अगला: Vectors →

चैलेंज से अभ्यास करें

इस पाठ में सीखी बात से एक असली समस्या हल करें। हर चैलेंज ब्राउज़र में चलता है, तुरंत टेस्ट और AI रिव्यू के साथ।

सभी चैलेंज