Array
The type of array is [T; Length], as you can see, array’s length is part of their type signature. So their length must be known at compile time.
For example, you cant initialize an array like below:
1. #![allow(unused)]
2. fn main() {
3. fn init_arr(n: i32) {
4. let arr = [1; n];
5. }
6. }
This will cause an error, because the compiler has no idea of the exact size of the array at compile time.
- 🌟
2. fn main() {
3. // Fill the blank with proper array type
4. let arr: __ = [1, 2, 3, 4, 5];
6. // Modify the code below to make it work
7. assert!(arr.len() == 4);
9. println!("Success!");
10. }
- 🌟🌟
2. fn main() {
3. // We can ignore parts of the array type or even the whole type, let the compiler infer it for us
4. let arr0 = [1, 2, 3];
5. let arr: [_; 3] = ['a', 'b', 'c'];
7. // Fill the blank
8. // Arrays are stack allocated, `std::mem::size_of_val` returns the bytes which an array occupies
9. // A char takes 4 bytes in Rust: Unicode char
10. assert!(std::mem::size_of_val(&arr) == __);
12. println!("Success!");
13. }
- 🌟 All elements in an array can be initialized to the same value at once.
2. fn main() {
3. // Fill the blank
4. let list: [i32; 100] = __ ;
6. assert!(list[0] == 1);
7. assert!(list.len() == 100);
9. println!("Success!");
10. }
- 🌟 All elements in an array must be of the same type
2. fn main() {
3. // Fix the error
4. let _arr = [1, 2, '3'];
6. println!("Success!");
7. }
- 🌟 Indexing starts at 0.
2. fn main() {
3. let arr = ['a', 'b', 'c'];
5. let ele = arr[1]; // Only modify this line to make the code work!
7. assert!(ele == 'a');
9. println!("Success!");
10. }
- 🌟 Out of bounds indexing causes
panic.
2. // Fix the error
3. fn main() {
4. let names = [String::from("Sunfei"), "Sunface".to_string()];
6. // `Get` returns an Option<&T>, it's safe to use
7. let name0 = names.get(0).unwrap();
9. // But indexing is not safe
10. let _name1 = &names[2];
12. println!("Success!");
13. }
You can find the solutions here(under the solutions path), but only use it when you need it
