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


#1

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

https://doc.rust-lang.org/std/io/trait.Write.html#implementors

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.


#2

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

let slice = &mut buf[..];

Which is an immutable binding to a mutable slice.


#3

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.


#5

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


#6

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