Casting pointers and intermediaries

I've been porting some old C/C++ code to Rust lately, and wanted to cast a sockaddr_ll to a function that takes a *const sockaddr.

&sall as *const sockaddr doesn't work, because the compiler plainly says that the conversion can't be done. I had a similar issue a while back, and Someone(tm) on some forum stated "just insert a as *const _ between the two and it'll probably work. Indeed it did, and it did this time as well.

I know _ is telling the compiler to infer what the type should be [if it can] -- but how does it reason to deduce what it needs to insert?

When you write an_immutable_ref as *const T, the type T can only be the same as the type of the immutable reference, so that's what it will pick for your underscore.

3 Likes

I realize I kind of asked the wrong question, but the way you answered it provided the answer I was actually looking for.

So basically rust allows pointer-to-pointer casts but it does not allow you to go directly from a &T to a *const U, one needs to first "bring &T into the pointer-world": &T -> *const T -> *const U.

Is this a somewhat correct mental model?

Exactly. If you want to go from &T to *const U, then Rust will make you be explicit about that by forcing you to cast twice.

2 Likes

Furthremore, it is recommended to use the .cast() method on raw pointers instead of ptr as *const T, so as to avoid accidentally mixing up (or introducing) mutability.

1 Like

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.