Reputation: 1796
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?
Upvotes: 3
Views: 3280
Reputation: 20649
There is a method str::as_mut_ptr
that does exactly this.
let mut str = "hello";
let r = str.as_mut_ptr(); // r: *mut u8
However, you are responsible for upholding the safety invariants of str
if you proceed to use r
. Quoting from the documentation (emphasis mine):
Converts a mutable string slice to a raw pointer.
As string slices are a slice of bytes, the raw pointer points to a
u8
. This pointer will be pointing to the first byte of the string slice.It is your responsibility to make sure that the string slice only gets modified in a way that it remains valid UTF-8.
Upvotes: 0
Reputation: 3171
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);
Upvotes: 3