Why is the #[lang = "unsafe_cell"] attribute strictly necessary for UnsafeCell?

⚓ Rust    📅 2026-06-16    👤 surdeus    👁️ 1      

surdeus

Hi everyone,

Based on my current understanding, UnsafeCell<T> is a primitive wrapper used to encapsulate a type, and the only way to access the inner value is by obtaining a raw pointer via the .get() method. Given that it already forces you to go through raw pointers, why does it specifically require the #[lang = "unsafe_cell"] attribute?

Scenario 1: Without this lang item, would the compiler still incorrectly optimize read behaviors (perhaps due to LLVM alias analysis)? For instance, in the snippet below:

use std::cell::UnsafeCell;

fn main() {
    let x = UnsafeCell::new(1);
    let y = x.get();
    
    // ... do something to mutate `x` via another pointer ...
    
    unsafe {
        println!("y: {}", *y);
    }
}

Could anyone provide a concrete example demonstrating what would break, or explain the exact compiler magic/optimizations that prove the absolute necessity of #[lang = "unsafe_cell"]?

Thanks in advance!

4 posts - 3 participants

Read full topic

🏷️ Rust_feed