just commenting that this section on slices (or rather sub-chapter) felt like a great read up (i've read up to chapter 8 so far)
the diagrams are very neat, and the explanations very clear.
just commenting that this section on slices (or rather sub-chapter) felt like a great read up (i've read up to chapter 8 so far)
the diagrams are very neat, and the explanations very clear.
i think the only doubt i got was whether one could use &mut s[..]
but it seems that this isn't possible, although in other cases mutable references are indeed mutable (like an item in a vec), but here it's not.
they only say:
The type of
s
here is&str
: it’s a slice pointing to that specific point of the binary. This is also why string literals are immutable;&str
is an immutable reference.
but &str
can be a pointer to String data on the heap as well.
I think this particular statement was meant to be about the specific value assigned to s
in the example right above it, not about &str
in general, though I can't refute that teaching materials can sometimes be somewhat confusing on this particular point (calling all kinds of types to be about values "on the stack" when in full generality it's more like "non necessarily on the heap, and if so, someone else than that value is owning the heap allocation").
yes, i agree, string literals are immutable due to &str
, but the reverse? can string slices be mutable (like in the case of s[..]
where s
is String
) ?
ps: from what i see elsewhere, one can replace parts, but not grow or shrink. this is slightly odd to me since refs to vectors can grow it I think.
Yes, string slices can be mutable - though because of the variable length encoding with UTF-8, there's barely any API that let's you mutate them
s[..]
- and indexing syntax in general - is a fun complication of its own anyway, given how slices are "unsized" types, the indexing notation is a "place expression" (a concept similar lvalue expression in C, AFAIK) and indexing can desugaring through one of two traits (Index
/IndexMut
) depending on the kind of access the expression is used in..
..with things like &s[..]
and &mut s[..]
using the full range on string slices (and ordinary slices) in particular, there's also a bit of a large number of syntactic alternatives, given the deref operator could also be used (like &*s
/ &mut *s
), or various explicit inherent methods (e. g. s.as_str()
for &str
from a String
) can be used, or the deref can often happen as an implicit coercion even, then s
or &s
or &mut s
might work directly (depending on the exact type of s
and the desired mutability).
interesting, that must be why it's left for later