Hi.
I am writing a whitelist struct that reads contents of a file and make a Hashset out of it and stores it inside struct.
Later in the program, i need to pass a reference of this struct to a closure to check the whitelist.
However, i don't know the right way to pass a reference of struct so that there is no performance penalty.
Maybe i am doing something wrong, i would be so happy if you help me correct it.
Thanks.
Create an Arc<WhiteList> and clone it for each spawn.
let whitelist = WhiteList::new();
// put stuff into the whitelist
// put it in an Arc (this makes it immutable)
let whitelist = Arc::new(whitelist);
loop {
let whitelist = Arc::clone(&whitelist);
tokio::spawn(async move {
// .. use whitelist here
});
}
This uses an Arc, which is a tool for sharing a value across many tasks or threads. Cloning an Arc is extremely cheap and does not clone the value inside it. Values are immutable once you put them in an Arc.
let whitelist = WhiteListInner::new();
// put stuff into the whitelist
// put it in an Arc (this makes it immutable)
let whitelist = WhiteList::new(whitelist);
loop {
let whitelist = whitelist.clone();
tokio::spawn(async move {
// .. use whitelist here
if whitelist.contains("foo") {
...
}
});
}