Why move happen?

I am writing a plugin for program written in C (wireshark) and wireshark initializes some structures in the plugin. So I do need mutable static structs in Rust. I made it work by creating a vector and doing mem::transmute but I wonder if it is possible to do it without copying to Vec and the way I would do it in C: just declare static array and passing pointer to array to Wireshark for initialization.

Here is minimized example of what is needed. I do not understand, why move happen. I am taking a reference to INSTANCE when creating array, so array should be initialized with pointer to INSTANCE, not with its copy?

extern "C" {
    pub fn register(hf: *mut ApiInitialized<i32>);
}
struct ApiInitialized<T>(T);
static mut INSTANCE: ApiInitialized<i32> = ApiInitialized(-1);
static mut LIST: [&ApiInitialized<i32>; 1] = [& unsafe {INSTANCE}];
fn init() {
    unsafe { register(LIST.as_mut_ptr() as *mut _); }
}

(Playground)

Errors:

   Compiling playground v0.0.1 (/playground)
error[E0507]: cannot move out of a raw pointer
 --> src/lib.rs:6:57
  |
6 | static mut LIST: [&ApiInitialized<i32>; 1] = [& unsafe {INSTANCE}];
  |                                                         ^^^^^^^^ move occurs because value has type `ApiInitialized<i32>`, which does not implement the `Copy` trait

For more information about this error, try `rustc --explain E0507`.
error: could not compile `playground` due to previous error

That error message is a little confusing since it references a "raw pointer" that isn't directly present in the code that's causing the error, but the problem is just that using a block of any type to return a value requires that you be able to move[1] the value.

If you do

unsafe {&INSTANCE}

it works fine, after fixing the visibility error that pops up.


  1. or copy ↩︎

Thank you!. Initially I had it without unsafe and followed Intellij's suggestion to fix it, which compiled and gave this strange error. The way you suggest makes much more sense, and if I fixed it on my own instead of relaying on help from IDE, I probably would end up with the right code :slight_smile:

Does IntelliJ use the rust analyzer and the rest of the Rust dev stack?… or it’s own?

Intellij use its own analyzer.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.