Info
This post is auto-generated from RSS feed The Rust Programming Language Forum - Latest topics. Source: Methods on static muts
Is there a way to call methods on static muts? The only workarounds i have found are to either use functions instead of methods or raw pointers.
struct A {
// Holds value that are expensive to clone
val: u64,
}
impl A {
fn get_ref(&self) -> u64 {
self.val
}
fn get_own(self) -> u64 {
self.val
}
fn get_mut(&mut self) -> u64 {
self.val
}
}
static mut HOLD: A = A {val: 0};
fn main() {
unsafe {
// Cant create a refernce to static mut
let a = HOLD.get_ref();
let b = HOLD.get_mut();
// Cant move out of static mut
let c = HOLD.get_own();
// Onyl workaround (Gets marked by clippy)
let d = (*(&raw const HOLD)).get_ref();
let e = (*(&raw mut HOLD)).get_ref();
}
}
fn b() -> u64 {
unsafe {
HOLD.val
}
}
3 posts - 3 participants
🏷️ Rust_feed