Description
I tried this code:
struct Foo {
a: u32,
}
impl Foo {
fn bar() -> &'static [usize] {
&[std::mem::offset_of!(Self, a)]
}
}
I expected to see this happen: no error
Instead, this happened:
error[E0515]: cannot return reference to temporary value
--> src/lib.rs:7:9
|
7 | &[std::mem::offset_of!(Self, a)]
| ^-------------------------------
| ||
| |temporary value created here
| returns a reference to data owned by the current function
For more information about this error, try `rustc --explain E0515`.
error: could not compile `playground` (lib) due to 1 previous error
Meta
rustc 1.79 nightly 2024-04-27
Activity
[-]`offset_of`[/-][+]`offset_of` returns a temporary[/+]tgross35 commentedon Apr 28, 2024
I can't think of any reason why it would create the temporary here, considering you can assign the result to a
const
just fine.cc @GKFX who worked on this most recently
@rustbot label +T-compiler +F-offset_of -needs-triage
GKFX commentedon Apr 28, 2024
It's the
core::hint::must_use
that does it: https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=bd518763786b97f87434d5c986cc52cf.builtin # offset_of
alone doesn't cause the problem.I'm not sure what the original reason was for making this
must_use
, or whether it would be OK to just remove it? Wrapping the macro inconst {}
works, but that would interfere with array indexing in offset_of if that ever gets supported.asquared31415 commentedon Apr 28, 2024
making it
must_use
makes sense, but if it's not possible to keep that behavior and make it not a temporary, i think it's better UX to remove themust_use
hint.GKFX commentedon Apr 28, 2024
@rustbot claim
Fix rust-lang#124478 - offset_of! returns a temporary
core::hint::must_use
returns a temporary #124493VertexBufferLayout
gfx-rs/wgpu#5621Rollup merge of rust-lang#124484 - GKFX:offset_of_must_use, r=jieyouxu
Auto merge of rust-lang#124527 - jieyouxu:rollup-eslzncy, r=jieyouxu
Unrolled build for rust-lang#124484