- Mastering Rust
- Rahul Sharma Vesa Kaihlavirta
- 409字
- 2021-07-02 13:35:18
Slices
Slices are a generic way to get a view into a collection type. Most use cases are to get a read only access to a certain range of items in a collection type. A slice is basically a pointer or a reference that points to a continuous range in an existing collection type that's owned by some other variable. Under the hood, slices are fat pointers to existing data somewhere in the stack or the heap. By fat pointer, it means that they also have information on how many elements they are pointing to, along with the pointer to the data.
Slices are denoted by &[T], where T is any type. They are quite similar to arrays in terms of usage:
// slices.rs
fn main() {
let mut numbers: [u8; 4] = [1, 2, 3, 4];
{
let all: &[u8] = &numbers[..];
println!("All of them: {:?}", all);
}
{
let first_two: &mut [u8] = &mut numbers[0..2];
first_two[0] = 100;
first_two[1] = 99;
}
println!("Look ma! I can modify through slices: {:?}", numbers);
}
In the preceding code, we have an array of numbers, which is a stack allocated value. We then take a slice into the array numbers using the &numbers[..] syntax and store in all, which has the type &[u8]. The [..] at the end means that we want to take a full slice of the collection. We need the & here as we can't have slices as bare values – only behind a pointer. This is because slices are unsized types. We'll cover them in detail in Chapter 7, Advanced Concepts. We can also provide ranges ([0..2]) to get a slice from anywhere in-between or all of them. Slices can also be mutably acquired. first_two is a mutable slice through which we can modify the original numbers array.
To the astute observer, you can see that we have used extra pair of braces in the preceding code when taking slices. They are there to isolate code that takes mutable reference of the slice from the immutable reference. Without them, the code won't compile. These concepts will be made clearer to you in Chapter 5, Memory Management and Safety.
Next, let's look at iterators.
- Java語言程序設(shè)計
- 從零構(gòu)建知識圖譜:技術(shù)、方法與案例
- Python從小白到大牛
- Ceph Cookbook
- PHP 7底層設(shè)計與源碼實現(xiàn)
- Windows Phone 7.5:Building Location-aware Applications
- Mastering openFrameworks:Creative Coding Demystified
- Android傳感器開發(fā)與智能設(shè)備案例實戰(zhàn)
- Mockito Essentials
- 硬件產(chǎn)品設(shè)計與開發(fā):從原型到交付
- Practical Predictive Analytics
- 川哥教你Spring Boot 2實戰(zhàn)
- IBM DB2 9.7 Advanced Application Developer Cookbook
- PhoneGap 3.x Mobile Application Development Hotshot
- 語義Web編程