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.
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