ADVERTISEMENT
ADVERTISEMENT

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

Rust | Vector Example: Write a program to create a vector using the new() method.
Submitted by Nidhi, on October 23, 2021

Problem Solution:

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.

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.

Rust Vectors Programs »



ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.