Mutable as_bytes() array?


Hi guys,

I am reading slices section in “the book”. It has an example of getting first word as following,

fn first_word(s : &String) -> usize{
    let mut bytes = s.as_bytes(); // is this mutable.
    bytes[1] = bytes[1] + 200;
    for (i, &item) in bytes.iter().enumerate(){
        if item == b' '{
            return i;


fn main() {
    let mut s = String::from("hello world");

    let word = first_word(&s);

In the first line of first_word I get an array of bytes as per the string characters. I see that


returns an immutable reference array. But I am saving it in mutable variable.

So, when I try to change the array, it is not allowing.
Why is this?


The let mut bytes gives you a reference that you can re-target (ie change where it points), but you cannot mutate the target itself.

To get a &mut str, which is reference that allows mutating the value behind the reference, you need to use as_bytes_mut(). For that method to be available, you need to have a &mut String but you have a &String. So in your main, you need to call the function like first_word(&mut s).


Thanks @vitalyd