Why can I use Write trait on a mut slice of u8

I am new to rust and I thought that the Write trait was implemented for a mut slice of u8.

As I am new a lot of things could be wrong.
The error message does not say mut so maybe I dont have a mut slice.
The lifetime is wrong as I don't understand that yet.
The version does not match the doc.

use std::io::Write;
fn main() {
    let mut buf : [u8;100] =[0;100];
    let mut slice = &buf[..];
    slice.write("Tests".as_bytes());
    
}

(Playground)

Errors:

   Compiling playground v0.0.1 (/playground)
error[E0599]: no method named `write` found for type `&[u8]` in the current scope
 --> src/main.rs:5:11
  |
5 |     slice.write("Tests".as_bytes());
  |           ^^^^^

error: aborting due to previous error

For more information about this error, try `rustc --explain E0599`.
error: Could not compile `playground`.

To learn more, run the command again with --verbose.

This creates a mutable binding to an immutable slice. You want

let slice = &mut buf[..];

Which is an immutable binding to a mutable slice.

1 Like

Hi, you want

let mut slice = &mut buf[..];

You need the first mut because the Write trait asks for a &mut self.
If you are unsure of the type of a variable you can always do

let _: () = <variable>;

and the compile will give you an error with the type of your variable.

1 Like

Thx for the quick answer I tried mut many places for some reason I prefer it before &.

Thanks you are right. Mut binding to change the slice and mut reference to change array.