Skip to content

CTFE cannot access any field of a static if a single one of them has interior mutability. #156789

@Authomats

Description

@Authomats

Code

struct ValidStruct {
    string: &'static str,
}

static VALID_STATIC: ValidStruct = ValidStruct {
    string: "Hello, world!",
};

const VALID_FIRST_BYTE: u8 = VALID_STATIC.string.as_bytes()[0];

struct ProblematicStruct {
    string: &'static str,
    cached_hash: std::sync::atomic::AtomicU64,
}

static PROBLEMATIC_STATIC: ProblematicStruct = ProblematicStruct {
    string: "Hello, world!",
    cached_hash: std::sync::atomic::AtomicU64::new(0),
};

// Throws error, despite only the `string` field being accessed:
// 
// constant accesses mutable global memory
// evaluation of `PROBLEMATIC_FIRST_BYTE` failed here
// 
const PROBLEMATIC_FIRST_BYTE: u8 = PROBLEMATIC_STATIC.string.as_bytes()[0];

fn main() {
    //
}

Current output

error[E0080]: constant accesses mutable global memory
  --> src/main.rs:26:36
   |
26 | const PROBLEMATIC_FIRST_BYTE: u8 = PROBLEMATIC_STATIC.string.as_bytes()[0];
   |                                    ^^^^^^^^^^^^^^^^^^^^^^^^^ evaluation of `PROBLEMATIC_FIRST_BYTE` failed here

Desired output

There should be no output, const values should be able to be computed this way.

Rationale and extra context

Compile-time function evaluation can access static values to compute const values, but it cannot do so if the static value has interior mutability, because the value produced by CTFE has to be the same every time. This makes sense (*).

What does, however, not make any sense, is that apparently a single field of a static variable having interior mutability causes the compiler to consider the entire static to have it and therefore all its other, effectively still const, fields to not be readable at compile-time, too.

I don't know if there is some bigger rationale behind this, that I have simply not found, but this seems like an error to me.

Other cases

Rust Version

rustc 1.97.0-nightly (e50aa6fba 2026-05-19)
binary: rustc
commit-hash: e50aa6fba4e63ab34c72bf9acfd2c307c1155d1a
commit-date: 2026-05-19
host: x86_64-unknown-linux-gnu
release: 1.97.0-nightly
LLVM version: 22.1.4

Anything else?

Sidenote: (*) I would argue that, since functions that can change interior mutable values are, as far as I know, never const themselves, more generally compile-time evaluation could simply use the value an interior mutable static was initialized to and let it get accessed via (non-mutable) references.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions