Rust is a strange language for some. However, it is a fun programming language to play (or work) with. When we need arrays in Rust, we declare and initialize an array simultaneously with size and default values.
Declare And Initialize Array Literals in Rust
Arrays store values of the same type. Therefore, we can create arrays of type i32, String, &str, and even struct. Consider the following sample codes that declare and initialize an array literal of i32 type with a size of 4.
1 2 3 4 5 6 7 8 | let my_integers = [1, 2, 3, 4]; // Same as: // let my_integers:[i32;4] = [1, 2, 3, 4]; for my_iny in my_integers.iter() { println!("{}", my_iny); } |
When we run the codes, we get the following output.
1 2 3 4 | 1 2 3 4 |
Let’s create another array sample. The following codes declare and initialize an array literal of &str type with 2 elements.
1 2 3 4 5 | let my_strings = ["AA", "BB"]; for my_str in my_strings.iter() { println!("{}", my_str); } |
When we run these codes, we get the following result.
1 2 | AA BB |
How about an array of struct instances? We can also declare and initialize an array of the Struct type. Consider the following codes. We have a struct Student that holds i32 and String values.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | struct Student { id: i32, name: String } fn main() { // my_students is implicitly my_students[Student:2] let my_students = [ Student { id: 1, name: String::from("Karl") }, Student { id: 2, name: String::from("Lucas") }]; for my_student in my_students.iter() { println!("ID={}; NAME={}", my_student.id, my_student.name); } } |
Then, we declare and initialize an array type Student. Note that we need to create instances of Student to supply the array with value for its initialization. When we run the codes, we get the following output.
1 2 | ID=1; NAME=Karl ID=2; NAME=Lucas |
Array with Default values
Sometimes it is cumbersome to initialize an array with values, especially when it’s relatively long. For example, we would need to provide integer values for an array with 100 elements explicitly. Fortunately, there’s a shortcut to that. We could declare and initialize an array with the same initial values and modify them later in the application. Consider the following sample codes below; we declare and initialize an array of size 5 with a default "[change me]".
1 2 3 4 5 6 7 8 | let mut top5_keywords = ["[change me]"; 5]; top5_keywords[0] = "Nirvana"; top5_keywords[4] = "RATM"; for keyword in top5_keywords.iter() { println!("Keyword={}", keyword); } |
With this shortcut, we only need to specify one default value for all elements of the array. When we run the codes, we get the following output.
1 2 3 4 5 | Keyword=Nirvana Keyword=[change me] Keyword=[change me] Keyword=[change me] Keyword=RATM |
We can use the same technique when declaring and initializing multi-dimensional arrays.