Gilnaa / memoffset

offsetof for Rust
MIT License
224 stars 29 forks source link

Compile error on const offset in struct with interior mutability #37

Closed hvenev closed 3 years ago

hvenev commented 4 years ago

Playground containing an extract of the code from the current master (d3f5f23483dc3b61746f041da4fc422e24316c96)

#[repr(C)]
struct Foo {
    a: core::sync::atomic::AtomicUsize,
}

assert_eq!([0; offset_of!(Foo, a)].len(), 0);

Building this fails with the following error:

error[E0492]: cannot borrow a constant which may contain interior mutability, create a static instead
  --> src/offset_of:112:66
    |
112 |             let base_ref = ::core::mem::transmute::<_, &$parent>(&uninit);
    |                                                                  ^^^^^^^
...
NNN |     assert_eq!([0; offset_of!(Foo, a)].len(), 0);
    |                    ------------------ in this macro invocation

Note that there is no error if Foo::a is usize instead.

RalfJung commented 3 years ago

@hvenev could you try this again with #![feature(const_cell_refs)] (https://github.com/rust-lang/rust/issues/79703)? That enables a more precise way to check what happens with references to interior mutable types.

RalfJung commented 3 years ago

Sorry, I meant const_refs_to_cell, tracked at https://github.com/rust-lang/rust/issues/80384.

hvenev commented 3 years ago

Yes, it appears to work on nightly: https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=bccaaea7e859e843018cc66e01880ed7

RalfJung commented 3 years ago

Great, thanks for testing. :)