Rust - Slices Flashcards
Describe pointers
A slice is a pointer to a block of memory.
Slices can be used to access portions of data stored in contiguous memory blocks.
It can be used with data structures like arrays, vectors and strings.
Slices use index numbers to access portions of data.
The size of a slice is determined at runtime.
What is the syntax
let sliced_data = &data_structure[start_index .. end_Index];
Give an example of a slice form of your name
fn main() {
let name = “Prince”. to_string();
let sliced_name = $name[2..5];
}
Give an example of slicing an integer array
fn main(){
let data = [10,20,30,40,50];
use_slice(&data[1..4]);
//this is effectively borrowing elements for a while
}
fn use_slice(slice:&[i32]) {
// is taking a slice or borrowing a part of an array of i32s
println!(“length of slice is {:?}”,slice.len());
println!(““,slice);
}
An example of a mutable slice
fn main(){
let mut data = [10,20,30,40,50];
use_slice(&mut data[1..4]);
// passes references of
20, 30 and 40
println!(““,data);
}
fn use_slice(slice:&mut [i32]) {
println!(“length of slice is {:?}”,slice.len());
println!(““,slice);
slice[0] = 1010; // replaces 20 with 1010
}