Why does it happen for String
and not for i32
?
The basic integral types (and in fact, many other types) in Rust implement the Copy
trait. They have "copy semantics", not "move semantics". There is no change of ownership here... you're copying out the value. String
does not implement the Copy
trait and therefore this binding has "move semantics".
This is not unique to raw pointers nor does it have anything to do with their mutability. This example shows this can happen with immutable references:
fn func(s: &String, a: &i32) {
let _x = *s;
let _x = *a;
}
Why is it complaining of a "move"?
It does this because you're attempting to move ownership out of the unsafe
block. As long as you're care-free about this then you need to contain the "move" within the unsafe
block so the compiler just lets you shoot yourself in the foot. As such, if you restructure your code so as to not move outside of the unsafe
block, the code will compile:
unsafe {
println!("{}", *s);
}
Here it is running in the playground.
To re-iterate Shepmaster's point in the comment on your question though... if the term "move" sounds foreign to you then you should not be using raw pointers/unsafe
blocks in the first place and should instead head back to the available documentation for Rust to understand the concept.. as it is a core one.
std::ptr::read
to copy out the raw string data, but that can easily result in undefined behaviour. – Telangiectasis