How do I create a global, mutable singleton?

前端 未结 3 1393
我在风中等你
我在风中等你 2020-11-21 06:59

What is the best way to create and use a struct with only one instantiation in the system? Yes, this is necessary, it is the OpenGL subsystem, and making multiple copies of

3条回答
  •  半阙折子戏
    2020-11-21 07:43

    Answering my own duplicate question .

    Cargo.toml:

    [dependencies]
    lazy_static = "1.4.0"
    

    Crate root ( lib.rs ):

    #[macro_use]
    extern crate lazy_static;
    

    Initialization ( no need for unsafe block ):

    /// EMPTY_ATTACK_TABLE defines an empty attack table, useful for initializing attack tables
    pub const EMPTY_ATTACK_TABLE: AttackTable = [
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    ];
    
    lazy_static! {
        /// KNIGHT_ATTACK is the attack table of knight
        pub static ref KNIGHT_ATTACK: AttackTable = {
            let mut at = EMPTY_ATTACK_TABLE;
            for sq in 0..BOARD_AREA{
                at[sq] = jump_attack(sq, &KNIGHT_DELTAS, 0);
            }
            at
        };
        ...
    

    EDIT:

    Managed to solve it with once_cell, which does not need a macro.

    Cargo.toml:

    [dependencies]
    once_cell = "1.3.1"
    

    square.rs:

    use once_cell::sync::Lazy;
    
    ...
    
    /// AttackTable type records an attack bitboard for every square of a chess board
    pub type AttackTable = [Bitboard; BOARD_AREA];
    
    /// EMPTY_ATTACK_TABLE defines an empty attack table, useful for initializing attack tables
    pub const EMPTY_ATTACK_TABLE: AttackTable = [
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    ];
    
    /// KNIGHT_ATTACK is the attack table of knight
    pub static KNIGHT_ATTACK: Lazy = Lazy::new(|| {
        let mut at = EMPTY_ATTACK_TABLE;
        for sq in 0..BOARD_AREA {
            at[sq] = jump_attack(sq, &KNIGHT_DELTAS, 0);
        }
        at
    });
    

提交回复
热议问题