Slices

Un slice ofrece una visión de una colección más amplia:

fn main() {
    let mut a: [i32; 6] = [10, 20, 30, 40, 50, 60];
    println!("a: {a:?}");

    let s: &[i32] = &a[2..4];

    println!("s: {s:?}");
}
  • Los slices toman prestados datos del tipo slice.
  • Pregunta: ¿Qué ocurre si se modifica a[3] justo antes de imprimir s?
This slide should take about 10 minutes.
  • Creamos un slice tomando prestado a y especificando entre paréntesis los índices de inicio y de fin.

  • Si el slice comienza en el índice 0, la sintaxis de rango de Rust nos permite eliminar el índice inicial, lo que significa que &a[0..a.len()] y &a[..a.len()] son idénticos.

  • Lo mismo ocurre con el último índice, por lo que &a[2..a.len()] y &a[2..] son idénticos.

  • Para crear fácilmente un slice del array completo, podemos usar &a[..].

  • s es una referencia a un slice de i32s. Ten en cuenta que el tipo de s (&[i32]) ya no menciona la longitud del array. Esto nos permite realizar cálculos en slices de diferentes tamaños.

  • Slices always borrow from another object. In this example, a has to remain ‘alive’ (in scope) for at least as long as our slice.

  • The question about modifying a[3] can spark an interesting discussion, but the answer is that for memory safety reasons you cannot do it through a at this point in the execution, but you can read the data from both a and s safely. It works before you created the slice, and again after the println, when the slice is no longer used.