- 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.
- Web應用系統開發實踐(C#)
- Docker and Kubernetes for Java Developers
- Docker進階與實戰
- PHP+MySQL網站開發技術項目式教程(第2版)
- 樂高機器人設計技巧:EV3結構設計與編程指導
- 技術領導力:程序員如何才能帶團隊
- Visual Basic程序設計教程
- jQuery從入門到精通 (軟件開發視頻大講堂)
- Kali Linux Wireless Penetration Testing Beginner's Guide(Third Edition)
- Getting Started with NativeScript
- C#開發案例精粹
- Mastering ArcGIS Enterprise Administration
- 詳解MATLAB圖形繪制技術
- 從零開始:UI圖標設計與制作(第3版)
- BeagleBone Robotic Projects(Second Edition)