How to create *mut u8 from Rust string?

Viewed 1272

I'm new to Rust. I want to create a mutable u8 buffer.

I tried

let mut str = "hello";
let r = str as *mut u8;

but I get

error[E0606]: casting `&str` as `*mut u8` is invalid

I want to know how but also why. What is the type of "hello"? How does casting works on Rust?

1 Answers

First: str doesn't need to be mutable because you are not mutating it. Second: 'hello' is of type &str (string slice). Third: You can convert &str to &[u8] by calling as_bytes() on it, which is the buffer you needed. Appending mut before the variable name makes it mutable.

   let str = "hello";
   let mut r = str.as_bytes();
   println!("{:?}", r);
Related