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

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.

主站蜘蛛池模板: 靖安县| 金秀| 宜昌市| 阳高县| 石狮市| 即墨市| 通山县| 安徽省| 应用必备| 丰宁| 昭平县| 湘潭市| 名山县| 新干县| 喀什市| 修武县| 西藏| 宝应县| 云林县| 余干县| 会理县| 呼伦贝尔市| 景德镇市| 南部县| 宜兰县| 宿松县| 崇阳县| 四平市| 新安县| 长寿区| 镇康县| 广西| 康保县| 茌平县| 红原县| 谢通门县| 天祝| 通辽市| 灵寿县| 陇南市| 府谷县|