fn func(s: *mut String, a: *mut i32) -> usize {
println!("{}", unsafe { *s });
println!("{}", unsafe { *a });
unsafe { (*s).len() }
}
fn main() {
let mut s = String::from("hello");
let mut a = 10;
func(&mut s, &mut a);
}
The above code fails with the error:
error[E0507]: cannot move out of dereference of raw pointer
--> src/main.rs:2:29
|
2 | println!("{}", unsafe { *s });
| ^^ cannot move out of dereference of raw pointer
Why does it happen for String and not for i32? Why is it complaining of a "move"?
The basic integral types (and in fact, many other types) in Rust implement the
Copytrait. They have "copy semantics", not "move semantics". There is no change of ownership here... you're copying out the value.Stringdoes not implement theCopytrait 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:
It does this because you're attempting to move ownership out of the
unsafeblock. As long as you're care-free about this then you need to contain the "move" within theunsafeblock 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 theunsafeblock, the code will compile: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/
unsafeblocks 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.