#lazy-static

mut_static

Provides a struct to help create mutable statics with lazy_static

7 releases (major breaking)

Uses old Rust 2015

5.0.0 May 13, 2017
4.0.0 Feb 10, 2017
3.0.0 Jan 2, 2017
2.0.0 Dec 31, 2016
0.1.0 Dec 19, 2016

#6 in #lazy-static

Download history 363/week @ 2024-07-25 280/week @ 2024-08-01 313/week @ 2024-08-08 370/week @ 2024-08-15 381/week @ 2024-08-22 289/week @ 2024-08-29 450/week @ 2024-09-05 511/week @ 2024-09-12 243/week @ 2024-09-19 302/week @ 2024-09-26 446/week @ 2024-10-03 434/week @ 2024-10-10 437/week @ 2024-10-17 448/week @ 2024-10-24 297/week @ 2024-10-31 311/week @ 2024-11-07

1,510 downloads per month
Used in 28 crates (13 directly)

MIT license

10KB
224 lines

mut_static

Provides a struct to help create mutable statics with lazy_static.

(crates.io)

Quickstart

To create a mutable static simply put your lazy_static object inside of a MutStatic:

use mut_static::MutStatic;
use std::mem;
use std::ops::DerefMut;

pub struct MyStruct { value: usize }

impl MyStruct {
    pub fn new(value: usize) -> Self {
        MyStruct{ value: value }
    }

    pub fn get_value(&self) -> usize {
        self.value
    }

    pub fn set_value(&mut self, value: usize) {
        self.value = value
    }
}

// Declaring a MutStatic
lazy_static! {
    pub static ref MY_STRUCT: MutStatic<MyStruct> = {
        MutStatic::new()
    };
}

// Declaring a MutStatic which already has data
lazy_static! {
    pub static ref MY_STRUCT_PRESET: MutStatic<MyStruct> = {
        MutStatic::from(MyStruct::new(0))
    };
}

fn main() {
    // Setting a MutStatic
    MY_STRUCT.set(MyStruct::new(0)).unwrap();

    // Using a MutStatic
    {
        let my_struct = MY_STRUCT.read().unwrap();
        assert!(my_struct.get_value() == 0);
    }

    // Using a MutStatic mutably
    {
        let mut my_struct = MY_STRUCT.write().unwrap();
        my_struct.set_value(1);
        assert!(my_struct.get_value() == 1);
    }

    // Resetting a MutStatic
    {
        let mut my_struct = MY_STRUCT.write().unwrap();
        mem::replace(my_struct.deref_mut(), MyStruct::new(2));
        assert!(my_struct.get_value() == 2);
    }
}

Dependencies

~71KB