rust-lang-nursery / lazy-static.rs

A small macro for defining lazy evaluated static variables in Rust.
Apache License 2.0
1.9k stars 111 forks source link

cannot create mutable static #161

Closed jschwinger233 closed 4 years ago

jschwinger233 commented 4 years ago
use lazy_static::lazy_static;
use tokio::runtime::Runtime;

lazy_static! {
    static ref RUNTIME: Runtime = Runtime::new().unwrap();
}

pub fn current_runtime() -> &'static mut Runtime {
    &mut RUNTIME
}

got

error[E0596]: cannot borrow immutable static item `RUNTIME` as mutable
 --> src/runtime.rs:9:5
  |
9 |     &mut RUNTIME
  |     ^^^^^^^^^^^^ cannot borrow as mutable

error[E0596]: cannot borrow data in a dereference of `runtime::RUNTIME` as mutable
 --> src/runtime.rs:9:5
  |
9 |     &mut RUNTIME
  |     ^^^^^^^^^^^^ cannot borrow as mutable
  |
  = help: trait `DerefMut` is required to modify through a dereference, but it is not implemented for `runtime::RUNTIME`

error: aborting due to 2 previous errors

did I miss something?

KodrAus commented 4 years ago

Hi @jschwinger23 :wave:

lazy_static doesn't allow you to get direct mutable access to the static value. You'll need to use some form of interior mutability, for example by wrapping your Runtime in a Mutex or RwLock and synchronize mutable access through that.

jschwinger233 commented 4 years ago

fair enough, thx