[Rust] About slice

고승우·2024년 7월 2일
0

Rust

목록 보기
8/16

Slice

Slice [T] is a region of an array or vector. Since u8 is just defined as a contiguous block of memory of type T, There's no compile time definition as to how large it is. That's why Slice can't put it on the stack. As a same word, Slice can not be defined as a local variable. That's the reason why Slices are always passed by reference.
The slice itself is the data(non sized). Many times though, people refer to &[T] as a slice

Reference to Slice

A Reference to a slice is a fat pointer.

Fat pointer comprises two word value
1. First element
2. The number of elements

// Example code
let v: Vec<f64> = vec![0.0, 0.707, 1.0, 0.707];
let a: [f64; 4] = [0.0, -0.707, -1.0, -0.707];
let sv: &[f64] = &v;
let sa: &[f64] = &a;

In the last two lines, Rust automatically converts the &Vec reference and the &[f64; 4] reference to slice references that point directly to the data.

Difference between Slice and Reference to

  • Slice
    • Unsized Type: length is known at run time
    • Represents Data: represents a potion of the data, but always needs to be referenced via a pointer (&[T])
  • Reference to Slice
    • Sized Type: contains
      1. A pointer to the first element in the slice
      2. The length of the slice
    • Can Be local Variable: includes both the pointer and length, the reference to the slice has a known size at compile time, making it possible to be used as a local variable
profile
٩( ᐛ )و 

0개의 댓글