w3resource

Rust Program: Create vector of mixed items

Rust Variables and Data Types: Exercise-10 with Solution

Write a Rust program that creates a vector of items containing different types of items. Print each item in the vector.

Sample Solution:

Rust Code:

fn main() {
    // Define a vector containing different types of items
    let items: Vec<(&str, i32, char, bool)> = vec![("apple", 10, 'A', true), ("banana", 20, 'B', false)];

    // Iterate over the vector and print each item
    for (name, quantity, grade, available) in &items {
        println!("Name: {}, Quantity: {}, Grade: {}, Available: {}", name, quantity, grade, available);
    }
}

Output:

Name: apple, Quantity: 10, Grade: A, Available: true
Name: banana, Quantity: 20, Grade: B, Available: false

Explanation:

Here is a brief explanation of the above Rust code:

  • 'fn main() { ... }': This is the program's entry point.
  • 'let items: Vec<(&str, i32, char, bool)> = vec![("apple", 10, 'A', true), ("banana", 20, 'B', false)];': This line defines a vector named 'items' containing tuples with different types of items. Each tuple consists of a string ('&str'), an integer ('i32'), a character ('char'), and a boolean ('bool').
  • 'for (name, quantity, grade, available) in &items { ... }': This line iterates over the vector 'items' using a tuple pattern to destructure each tuple into its components ('name', 'quantity', 'grade', 'available'). It then prints each item's components using 'println!'.

Rust Code Editor:

Previous: Rust Program: Define character variable with first initial.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.