Why does rust documentation say slices are read-only?

While reading the Vec documentation, I came across the following statement.

A Vec can be mutable. On the other hand, slices are read-only objects.

In Rust, it’s more common to pass slices as arguments rather than vectors when you just want to provide read access.

However slices and Vec can both be mutable as shown in the following example (From slice documentation)

let mut x = [1, 2, 3];
let x = &mut x[..]; // Take a full slice of `x`.
x[1] = 7;
assert_eq!(x, &[1, 7, 3]);

Can someone please help me understand the statement from the Vec documentation.

Thanks in advance.

1 Like

I think the meaning was that you can't add or remove elements from a slice, but you can with a Vec. When it comes to mutating the elements themself however they are equivalent. The documentation is pretty misunderstandable though.

9 Likes

"Slices are immutable" is not a great way to put it. Just like any other type, slices aren't inherently mutable or immutable.

If you take a mutable reference to a slice, you can mutate its elements. If you take a shared reference to a slice, you may or may not be able to mutate its elements (depending on whether the elements themselves contain interior mutability).

I agree that it probably wanted to express that the length of a slice can't be changed, but the phrasing is certainly ambiguous at best, misleading/incorrect at worst.

4 Likes

This is one case where the official documentation (and most other places) use pretty sloppy terminology. "Slice" is used for all of

  • [T] which is unsized
  • &[T] which is a shared (T may or may not have or contain shared mutability, but you can't replace any element itself say)
  • &mut [T] which is exclusive (each element can be replaced or mutated)

And with &[T] or &mut [T], the reference-to-slice may itself be mutable (so you can make it point to a different slice). For example consider this implementation of Read for &[u8], where the shared slice (Self: &[u8]) is shortened when bytes are read.

The documentation on that page should definitely be improved.

8 Likes

Now you're getting into the philosophical problem of whether an e.g. i32 is "actually" mutable or just replaceable, but that's eventually a "no true Scotsman" argument that nobody wins.

Easier to talk about whether a "place" (result of an expression) is mutable, perhaps, rather than a type.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.