Working with Loops on Array
The following example iterates through an array and prints the indexes and their corresponding values. The loop retrieves values from index 0 to 4 (index of the last array element).
In this example, an array is iterated by a loop and prints the index and the value. Loop retrieves the value from 0 to 5
Rust
fn main(){ let gfg_array:[i32;5] = [1,2,3,4,5]; println!( "array is {:?}" ,gfg_array); println!( "array size is :{}" ,gfg_array.len()); for index in 0..5 { println!( "index is: {} & value is : {}" ,index,gfg_array[index]); } } |
Output:
array is [1, 2, 3, 4, 5]
array size is :5
index is: 0 & value is : 1
index is: 1 & value is : 2
index is: 2 & value is : 3
index is: 3 & value is : 4
index is: 4 & value is : 5
Rust – Array
An Array in Rust programming is a fixed-sized collection of elements denoted by [T; N] where T is the element type and N is the compile-time constant size of the array.
We can create an array in 2 different ways:
- Simply a list with each element [a, b, c].
- Repeat expression [N, X]. This will create an array with N copies of X.
[X,0] It is allowed but can cause some hectic problems so if you are using this type of expression be mindful of side effects. Array size from 0-32 implements the default trait if allowed by its type. Trait implementations are up to 32 sizes. An array is not iterateable itself.
Syntax:
ArrayType : [ Type ; Expression]
An array is written as:
let array: [i32; 3] = [4, 5, 6];
Contact Us