Skip to content

allow constants to refer to mutable/external memory, but reject such constants as patterns #1859

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

RalfJung
Copy link
Member

Reference update for rust-lang/rust#140942.

@ehuss
Copy link
Contributor

ehuss commented Jun 15, 2025

I'm trying to figure out, which reference rule rejects the following?

static mut S: i32 = 1;
const C: &mut i32 = unsafe { &mut S }; // ERROR: constructing invalid value

What I'm getting at, is that it seems like despite removing items.const.final-value-immutable, it seems like there is still some restriction somewhere. What I'm thinking:

  • final value of &mut — never ok?
  • final value of & of a static mut — now ok
  • final value of & of something with interior mutability — sometimes ok?

Is there maybe still some "final value must not have mutable references" restriction?


Is there some rule in the reference that would explain the following?

const C: &AtomicU32 = &AtomicU32::new(1);  // ERROR: constants cannot refer to interior mutable data

It seems like a pretty strong blanket statement that "constants cannot refer to interior mutable data", but the AtomicU32 example from rust-lang/rust#140942 seems like you can refer to interior mutable data. What exactly is the difference between a reference to a static versus a reference to a value created in the initializer?


Similarly, I'm trying to understand E0764. Is the description of E0764 out of date?

const C: &mut i32 = &mut 1; // ERROR: mutable references are not allowed in the final value of constants

Questions:

  • Is there a rule in the reference that explains this error?
  • "Mutable references (&mut) can only be used in constant functions, not statics or constants." seems to be wrong now, as you can use mutable references in statics or constants (with some limitations), right?
  • "Remember: you cannot use a function call inside a constant or static"... I...don't understand this at all. The example below it clearly shows using a function call inside a constant. I can't even guess what this is trying to say.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
S-waiting-on-review Status: The marked PR is awaiting review from a maintainer
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants