In Rust programs we have arrays, slices, and vectors and they often can be used interchangeably. We can initialize them with a variety of syntax forms.
With an array or vector, if we take a reference, we can get a slice. The slice can be used as a type in function arguments for more versatile code.
This example initializes vectors, slices and arrays in a variety of ways. For slices, we have to create a vector or array and take a reference to part of it.
String
vector, make sure to use to_string()
. String
literals are "str
" references, not Strings.push()
to append to a vector, or extend_from_slice
which is faster.fn main() { // Vector. let animals = vec!["bird", "frog", "dog"]; println!("{:?}", animals); // Vector. let animals = vec!["bird".to_string(), "frog".to_string()]; println!("{:?}", animals); // Array. let animals = ["bird", "frog", "dog"]; println!("{:?}", animals); // Slice of array. let animals_slice = &animals[0..2]; println!("{:?}", animals_slice); // Vector. let mut animals = Vec::with_capacity(2); animals.push("bird"); animals.push("frog"); animals.push("dog"); println!("{:?}", animals); // Slice from vector. let animals_slice = animals.as_slice(); println!("{:?}", animals_slice); // Array. let numbers = [0; 10]; println!("{:?}", numbers); // Array. let numbers: [u8; 5] = [1; 5]; println!("{:?}", numbers); // Array. let numbers = [1, 2, 3, 4, 5, 6, 7]; println!("{:?}", numbers); // Slice. let numbers_slice = &numbers[0..2]; println!("{:?}", numbers_slice); // Slice. let numbers_slice = &numbers[..2]; println!("{:?}", numbers_slice); // Slice. let numbers_slice = &numbers[4..]; println!("{:?}", numbers_slice); // Slice. if let Some(numbers_slice) = numbers.get(1..3) { println!("{:?}", numbers_slice); } // Vector. let mut numbers = vec![]; let numbers_slice = [10, 20, 30]; numbers.extend_from_slice(&numbers_slice); println!("{:?}", numbers); }["bird", "frog", "dog"] ["bird", "frog"] ["bird", "frog", "dog"] ["bird", "frog"] ["bird", "frog", "dog"] ["bird", "frog", "dog"] [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] [1, 1, 1, 1, 1] [1, 2, 3, 4, 5, 6, 7] [1, 2] [1, 2] [5, 6, 7] [2, 3] [10, 20, 30]
After reviewing these initialization examples, it becomes clear that slices are "views" of existing data like arrays or vectors.
struct
, we should use Vectors or arrays—not slices.The get()
function is similar to taking a slice, but it returns an Option
. To deal with the Option
in the clearest way, we can use the if let Some syntax.
In Rust we can allocate vectors and arrays. For vectors, we often use the "vec
" macro. And slices can take references to ranges of vectors and arrays in a unified way.