Primitive Type Array
A fixed-size array, denoted [T; N], for the element type, T, and the non-negative compile-time constant size, N.
Primitive Type array, std docs
There are two syntactic forms for creating an array:
- A list with each element, i.e., [x, y, z].
- A repeat expression [x; N], which produces an array with N copies of x. The type of x must be Copy.
- [expr; 0] is allowed, and produces an empty array. This will still evaluate expr, however, and immediately drop the resulting value, so be mindful of side effects.
Examples,
#![allow(unused)] fn main() { let mut array: [i32; 3] = [0; 3]; array[1] = 1; array[2] = 2; println!("{:?}", array); // -> [0, 1, 2] println!("{:?}", &array); //-> [0, 1, 2] // get a slice from array[n..m] // from nth position to mth position(excluding) println!("{:?}", &array[1..]); //-> [1, 2] println!("{:?}", &array[..]); // -> [0, 1, 2] println!("array.len(): {}", array.len()); // -> array.len(): 3 println!("{:?}", &array[..array.len() - 1]); // => [0, 1] println!("{:?}", &array[..array.len()]); // -> [0, 1, 2] println!("{:?}", &array[array.len()..array.len()]); // -> [] assert_eq!([1, 2], &array[1..]); // This loop prints: 0 1 2 // for x in array { } // error: the trait bound `[i32; 3]: std::iter::Iterator` is not satisfied for x in &array { print!("{} ", x); //-> 0 1 2 } println!("using array.iter()"); for x in array.iter() { print!("{} ", x); //-> 0 1 2 } }
You can use a slice pattern to move elements out of an array:
// The following example is not working, to be continued!!!
fn main() { fn move_away(a: str) -> str { /* Do interesting things. */ a.to_uppercase() } let [mut john, roa] = ["John".to_string(), "Roa".to_string()]; john = move_away(&john); // move_away(roa); println!("{:?}", john); println!("{:?}", john); }
以下:分かりません