Q:

Rust program to create a vector using the new() method

belongs to collection: Rust Vectors Programs

0

In this program, we will create a vector of string elements using the new() method then we will add items into the created vector using the push() method.

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 create a vector using the new() method is given below. The given program is compiled and executed successfully.

// Rust program to create a vector 
// using new() method

fn main() {
   let mut countries: Vec<&str> = Vec::new();
   let mut index:usize=0;
   
   countries.push("INDIA");
   countries.push("USA");
   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 using the new() method to store the name of countries. Then we added items into created vector. After that, we printed the elements of the vector.

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

total answers (1)

Rust program to iterate the items of the vector us... >>
<< Rust program to access vector elements using get()...