Q:

Rust program to access vector elements using the index

belongs to collection: Rust Vectors Programs

0

In this program, we will create a vector to store the name of countries then we will access the elements of the vector using the index.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

The source code to access vector elements using the index is given below. The given program is compiled and executed successfully.

// Rust program to access vector elements 
// using index

fn main() {
   let mut countries = vec!["INDIA","USA"];
   let mut index:usize=0;
   
   countries.push("UK");
   countries.push("CANADA");
   countries.push("ENGLAND");
   
   println!("Countries are: ");
   while index <countries.len()
   {
        println!(" {}", countries[index]);
        index=index+1;
   }
}

Output:

Countries are: 
 INDIA
 USA
 UK
 CANADA
 ENGLAND

Explanation:

Here, we created a vector to store the name of countries, and then we performed a PUSH operation to add the item into the vector. After that, we accessed the elements from the vector and printed them.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Rust program to access vector elements using get()... >>
<< Rust program to perform the POP operation...