Rust - Slices Flashcards

1
Q

Describe pointers

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is the syntax

A

let sliced_data = &data_structure[start_index .. end_Index];

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Give an example of a slice form of your name

A

fn main() {
let name = “Prince”. to_string();
let sliced_name = $name[2..5];
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Give an example of slicing an integer array

A

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);
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

An example of a mutable slice

A

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
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q
A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly