0

Is it possible to have a mutable non-static global variable in Rust?

Say I wanted this:

pub let foo: u64 = 47;

This will not work, as rust does not allow the let keyword outside of a function.

Chayim Friedman
  • 47,971
  • 5
  • 48
  • 77
CATboardBETA
  • 418
  • 6
  • 29

1 Answers1

-5

Create a container structure:

pub struct FooContainer {
    pub foo: u64,
}

pub const foo: FooContainer = FooContainer { foo: 47 };

You can now access it via

mod foovar;

pub main() {
    println!("{}", foovar::foo.foo)
}

Your instantiation of the struct can remain const since it's field foo is still mut.

CATboardBETA
  • 418
  • 6
  • 29
  • Now it does not raise a syntax error but [just prints 47 twice](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=832059bc21ab488dad3733591d9cd343) (and raises a warning for trying to mutate a constant, and correctly so). – Chayim Friedman Apr 12 '22 at 12:07
  • 1
    @CATboardBETA you seem to be deeply misunderstanding the behaviour of `const`. Semantically, the `const` value is copied to its point of use (think of it as a const always being inlined, and behaving such as far as the compiler is concerned). So you can assign to the const item because in reality a copy is instantiated locally, its attribute is updated, then the copy is dropped. That has no effect. Or at least not that of being a shared mutable global, assuming that's what you were looking for. – Masklinn Apr 12 '22 at 12:45
  • 1
    This doesn't work. If you're going to try to do a self-answer, at least make sure you test it first to see if actually does what you think. – Herohtar Apr 12 '22 at 15:12