官术网_书友最值得收藏!

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.

Note: The &str type also comes under the category of a slice type (a [u8]). The only distinction from other byte slices is that they are guaranteed to be UTF-8. Slices can also be taken on Vecs or Strings.

Next, let's look at iterators.

主站蜘蛛池模板: 华宁县| 澄迈县| 长海县| 永济市| 申扎县| 西乌珠穆沁旗| 海南省| 根河市| 定远县| 阳江市| 潮安县| 揭东县| 彰化县| 武强县| 凤台县| 瓦房店市| 通江县| 南江县| 黔南| 清镇市| 南溪县| 和平区| 青田县| 宾川县| 青海省| 乐都县| 西安市| 吉隆县| 德江县| 长寿区| 宜都市| 阿拉善盟| 冀州市| 博湖县| 华宁县| 凌云县| 泽库县| 枣强县| 商丘市| 宜兰市| 加查县|