Why do we have to cast to "_"?

let data: gpointer = ...
let gtk_socket: *mut gtk::ffi::GtkSocket = data as *mut _ as *mut gtk::ffi::GtkSocket;
I'm specifically referring to the "as *mut _" part.
Why do we have to cast to "_" ???

To answer that you first need to know that _ in Rust usually means "let the compiler infer the type".

With that in mind, something like &mut u64 as *mut u64 means cast a a specific exclusive borrow type to a specific raw mutable pointer type.

The final step then is
&mut u64 as *mut _
instead of
&mut u64 as *mut u64.
This means essentially: cast the exclusive borrow to a raw mutable pointer to another type T, but let the compiler infer what T should be.

1 Like

Hi and thanks, but:
I did know that the _ means let the compiler deduce the type, but my question is, perhaps, why do we have that step that is "as *mut _" in that chain of casting, instead of just data as *mut gtk::ffi::GtkSocket?

Because you can only cast from &mut T to *mut T while you can cast *mut T to *mut V for any T and V (well, almost any T and V). You can look at the rules here.

2 Likes