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];
Features of an Array
- Memory blocks in the array are in sequential order.
- Once an array is created it cannot be resized which means the array is static.
- The array element is represented by the memory block
- To identify array elements we use a unique integer known as a subscript.
- Putting values in the array element is known as array initialization.
- Values in the array element can be updated or modified but cannot be deleted.
Declaring and Initializing Arrays
The below-given surtaxes can be used to declare and initialize an array in Rust:
Syntax1:
let variable_name = [value_1,value_2,value_3];
Syntax2:
let variable_name:[dataType;array_size] = [value_1,value_2,value_3];
Syntax3:
let variable_name:[dataType;array_size] = [default_value_for_elements;array_size];
The value of the datatype is getting from the data type of the first variable of the array.
Printing Elements of a Simple Array
To print all values in the array use the {:?} syntax of the println!() function. To compute the size of the array we can use the len() function.
Example 1: Printing Elements in the array
Rust
#![allow(unused)]
fn main() {
let mut array: [i32; 5] = [0; 5];
array[1] = 1;
array[2] = 2;
array[3] = 3;
array[4] = 4;
assert_eq!([1, 2 , 3 ,4], &array[1..]);
for x in &array {
print!( "{} " , x);
}
}
|
Output:
0 1 2 3 4
Example 2: Printing Elements in the array
Rust
fn main(){
let arr:[i32;5] = [1,2,3,4,5];
println!( "array is {:?}" ,arr);
println!( "array size is :{}" ,arr.len());
}
|
Output:
array is [1, 2, 3, 4, 5]
array size is :5
Working with Arrays without Data Type
The program below declares an array of 5 elements. Here we are not explicitly defining the data type during variable declaration. So, the array will be of type integer. To compute the size of the array we can use the len() function.
Rust
fn main(){
let arr = [1,2,3,4,5];
println!( "array is {:?}" ,arr);
println!( "array size is :{}" ,arr.len());
}
|
Output:
array is [1, 2, 3, 4, 5]
array size is :5
Array Default Values
Let us create an array and initialize all the values with the default value 0.
Rust
fn main() {
let gfg_array:[i32;5] = [0;5];
println!( "array is {:?}" ,gfg_array);
println!( "array size is :{}" ,gfg_array.len());
}
|
Output:
array is [0, 0, 0, 0, 0]
array size is :5
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
Using the iter() Function on Arrays
The iter() function fetches values of all elements in an array.
Rust
fn main(){
let arr:[i32;5] = [1,2,3,4,5];
println!( "array is {:?}" ,arr);
println!( "array size is :{}" ,arr.len());
for val in arr.iter(){
println!( "value is :{}" ,val);
}
}
|
Output:
array is [1, 2, 3, 4, 5]
array size is :5
value is :1
value is :2
value is :3
value is :4
value is :5
Concept of Mutable Array
To declare the mutable array we use “mut” key. Mutable arrays are those arrays whose elements can be altered. See the example below for a better understanding.
Rust
fn main(){
let mut arr:[i32;5] = [1,2,3,4,5];
arr[1] = 0;
println!( "{:?}" ,arr);
}
|
Output:
[1, 0, 3, 4, 5]
We have updated the value of the array at index number “1” and print the value.
Passing Arrays as Parameters to Functions
We can pass an array as a parameter either by a call by value or call by reference to a function.
Example 1: Pass by value
Rust
fn main() {
let gfg_array = [1,2,3,4];
change_array(gfg_array);
print!( "Original array {:?}" ,gfg_array);
}
fn change_array( mut gfg_array:[i32;4]){
for i in 0..4 {
gfg_array[i] = 0;
}
println!( "Changed array {:?}" ,gfg_array);
}
|
Output:
Changed array [0, 0, 0, 0]
Original array [1, 2, 3, 4]
Example 2: Pass by reference
Rust
#![allow(unused)]
fn main() {
let mut gfg_array = [1,2,3,4,5];
change_array(& mut gfg_array);
print!( "Original array {:?}" ,gfg_array);
}
fn change_array(gfg_array:& mut [i32;5]){
for i in 0..5 {
gfg_array[i] = 0;
}
println!( "Changed array {:?}" ,gfg_array);
}
|
Output:
Changed array [0, 0, 0, 0, 0]
Original array [0, 0, 0, 0, 0]
Similar Reads
R - Array
Arrays are essential data storage structures defined by a fixed number of dimensions. Arrays are used for the allocation of space at contiguous memory locations. In R Programming Language Uni-dimensional arrays are called vectors with the length being their only dimension. Two-dimensional arrays are
12 min read
ES6 Array
An array is a homogeneous collection of values. It is a single variable that is used to store different elements. It is often used when we want to store a list of elements and access them by a single variable. Unlike most languages where the array is a reference to the multiple variables, an ES6 arr
5 min read
Swift - Arrays
An array is one of the most powerful data structures in any programming language. It is used to store elements of similar data types. In other words, suppose we want to store a number of values that are of integer type only then in such cases we can use an array of integers, if values are of type fl
9 min read
C++ Arrays
In C++, an array is a derived data type that is used to store multiple values of similar data types in a contiguous memory location. Each element can be accessed using its index (position starting from 0). Create ArrayIn C++, we can create/declare an array by simply specifying the data type first an
11 min read
Rust - For and Range
Suppose you have a list of items and you want to iterate over each item in the list. One thing we can do is use a for loop. Using a for loop, we can iterate over a list of items. In Rust, we use the keyword for in followed by the variable name or the range of items we want to iterate over. Let's see
4 min read
Scala | Arrays
Array is a special kind of collection in scala. it is a fixed size data structure that stores elements of the same data type. The index of the first element of an array is zero and the last element is the total number of elements minus one. It is a collection of mutable values. It corresponds to arr
6 min read
Kotlin Array
Array is one of the most fundamental data structure in practically all programming languages. The idea behind an array is to store multiple items of the same data-type,such as an integer or string under a single variable name. Arrays are used to organize data in programming so that a related set of
6 min read
Rust - Literals
A literal is a source code that represents a fixed value and can be represented in the code without the need for computation. The compiler uses by default i32 for integers and f64 for float types/. In Rust, literals are described by adding them in the type as a suffix. Example: Integer literal 6 has
1 min read
Rust - Creating a Library
Rust is a multi-paradigm programming language like C++ syntax that was designed for performance and safety, especially for safe concurrency. Also, it is a compiled system programming language. In this article, we will see how to create libraries in Rust. Creating a Rust Library:Step 1: We start by c
1 min read
Rust - HashMaps
The concept of HashMap is present in almost all programming languages like Java, C++, Python, it has key-value pairs and through key, we can get values of the map. Keys are unique no duplicates allowed in the key but the value can be duplicated. 1. Insertion In HashMap : To insert a value in a HashM
4 min read