Transmuting to &'static in order to move it into an async tokio task

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

surdeus

use tokio::task;
use std::sync::Arc;

#[tokio::main]
async fn main() {
    let num = Arc::new(5u32);
    let cloned = Arc::clone(&num);
    
    let r = &*num;
    
    let r: &'static u32 = unsafe { std::mem::transmute(r) };
    
    task::spawn(async move {
        println!("{num}");
        println!("{r}");
    });
    
    println!("{cloned}");
}

Is this code always sound? My thought process is that since both the referenced value and the static ref is moved into the same scope, the static ref is always valid in the case if the moved Arc pointer was the only one alive. Since only the Arc pointer gets moved, and not the pointed to value, the reference doesn't get invalidated. Is my reasoning correct or no? I checked with Miri and it didn't detect any UB, but of course it doesn't mean there aren't any undetected UB.

16 posts - 3 participants

Read full topic

🏷️ Rust_feed