How to create a share data in mod

how to create a share data in mod?

i hope implement the functional like below javascript code.

Try and avoid globals as much as you can, it's code smell and it makes your code harder to reason about.

If you really need gobals, then consider either lazy_static or once_cell to do the job. lazy_static is more popular, but once_cell is easier to use (as it doesn't use macros) and once_cell is easier to embed in other parts of the system.

with lazy_static

lazy_static::lazy_static! {
    static ref BROWSERS: Vec<Browser> = vec![];
}

with once_cell

use once_cell::sync::Lazy;

static BROWSERS: Lazy<Vec<Browser>> = Lazy::new(|| vec![]);

actually, my code is like this , i hope that i can use the browsers data in function to_string and random in struct Browser 's implement block.

now, i need not to modify it , it will be read-only.

In that case you can wrap it in a mutex,

with lazy_static

use std::sync::Mutex;

lazy_static::lazy_static! {
    static ref BROWSERS: Mutex<Vec<Browser>> = Mutex::new(Vec::new());
}

with once_cell

use once_cell::sync::Lazy;
use std::sync::Mutex;

static BROWSERS: Lazy<Mutex<Vec<Browser>>> = Lazy::new(|| Mutex::new(Vec::new()));

Then you can lock the mutex to gain write access to the vector


But why do you need a global registry of all browers?

actually , i don't need it is global data. i need access the same data in to_string ,random and so on.

Then why are you making a global (static)?

Also, to_string usually comes from the ToString trait, which is auto-implemented for all types that implement Display. So it is better to implement Display because you can then easily use that with println and friends.

So, does random give a random browser from the list of browsers?

The first , because i don't know that how to create a data and it is only used in a struct's implement.

and the second , the random function is used get a random browser from browsers.

Or i can implement a static function to get browsers?

impl Browser {

    pub fn get_browsers() -> Vec<Browser>{
        return vec![Browser{
             ...
       }];
   }
}

This could work.

If you know all the browsers up front you could even put them in an array to avoid an allocation, but that's not necessary.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.