Rust program to access vector elements using get() function

Rust | Array Example: Write a program to access vector elements using get() function.
Submitted by Nidhi, on October 23, 2021

Problem Solution:

In this program, we will create a vector of character elements then we will access the elements of the vector using the get() function.

Program/Source Code:

The source code to access vector elements using the get() function is given below. The given program is compiled and executed successfully.

// Rust program to access vector elements 
// using get() function

fn value(n:Option<&char>) 
{ 
    match n 
    { 
        Some(n)=>print!("{} ",n), 
        None=>println!("None"), 
    } 
}

fn main() {
   let mut vItems = vec!['A','B','C','P','L'];
   let mut index:usize=0;
   
   println!("Vector elements are: ");
   while index <vItems.len()
   {
        let ch: Option<&char> = vItems.get(index);
        value(ch);
        index=index+1;
   }
}

Output:

Vector elements are: 
A B C P L

Explanation:

Here, we created a vector of character elements. Then we accessed the elements of the vector using the get() function and printed them.

Rust Vectors Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.