book icon indicating copy to clipboard operation
book copied to clipboard

Do not use `as` to convert reference to pointer

Open SoniEx2 opened this issue 3 years ago • 6 comments

  • [x] I have checked the latest main branch to see if this has already been fixed
  • [x] I have searched existing issues and pull requests for duplicates

URL to the section(s) of the book with this problem:

https://doc.rust-lang.org/book/ch19-01-unsafe-rust.html#dereferencing-a-raw-pointer

Description of the problem:

This uses as to convert the reference to a pointer. We've ran into issues in the past with as, e.g. https://github.com/RustyYato/cell-project/pull/4. Specifically, it breaks inference in a bad way.

Suggested fix:

Use type ascription instead of as, e.g. let r1: *const i32.

SoniEx2 avatar Aug 11 '22 19:08 SoniEx2

we can't remember what we were doing where it broke inference... we're struggling to figure out a test case which demonstrates it tho. sorry about that.

SoniEx2 avatar Aug 27 '22 13:08 SoniEx2

found it: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=4a7780954f610b8c4adff2d19925b824

(ps: we believe this example to be unsound, specifically due to the Drop impl, but we digress. the main thing we're trying to point out is the difference between as and type ascription and the Drop impl doesn't actually matter for that.)

SoniEx2 avatar Aug 27 '22 16:08 SoniEx2