Why dereferencing moves... But not always?

In a bit more detail:

https://doc.rust-lang.org/reference/expressions/operator-expr.html#the-dereference-operator

The * (dereference) operator is also a unary prefix operator. When applied to a pointer it denotes the pointed-to location. If the expression is of type &mut T and *mut T , and is either a local variable, a (nested) field of a local variable or is a mutable place expression, then the resulting memory location can be assigned to. Dereferencing a raw pointer requires unsafe .

*x will create a place expression (think of this as an lvalue from C++). If you use this place expression directly, you will either have to move or copy it. This is why *nd as i32 == 0 fails. However, if you use it indirectly, i.e. by accessing a field, then you don't have to move or copy the entire place expression (only the parts that are used). This is why (*cd).field == 0 succeeds, it only needs to access field (which is Copy)

4 Likes