#How do I use a `Set` in Rust?

20 messages · Page 1 of 1 (latest)

dusky root
#

Hello. I'm trying to convert this simple TypeScript code to Rust:

const FRUITS = new Set(["apple", "banana"]);

function isFruit(thing: string): boolean {
  return mySet.has(thing);
}

I tried asking ChatGPT, but it gave me a solution that was either using unsafe (which is bad) or using lazy_static (which is an extra dependency).
Is there not a simple way to do this code in Rust with just the standard library?

earnest pendant
#

HashSet in the standard lib is what you're looking for

remote rapids
autumn shoal
#

making a hashset in global contexts may be more difficult

#

if a given set is small enough i'd just use an array inside is_fruit and use contains

dusky root
#

Yes, I'm looking to just make a hash set that exists for the context of the entire program.

#

if a given set is small enough i'd just use an array inside is_fruit and use contains
Is that best practice? It won't be O(1) anymore, right?

autumn shoal
#

well, good thing OnceLock is stabilized, which means you could write this with less boilerplate than before, but still not good compared to using a phf or a Lazy from once_cell

autumn shoal
dusky root
#

Oh, I see.

#

Is there a rough guideline where > N would make hashing worth it?

autumn shoal
#

depends on the type, but i usually see ppl say around a 100

#

?play

use std::sync::OnceLock;
use std::collections::HashSet;

static FRUITS: OnceLock<HashSet<&'static str>> = OnceLock::new();

fn fruits_init() -> HashSet<&'static str> {
    HashSet::from(["apple", "banana"])
}

fn is_fruit(thing: &str) -> bool {
    FRUITS.get_or_init(fruits_init).contains(thing)
}
marsh spokeBOT
autumn shoal
#

this is a translation of ur code, assuming you don't want dependencies

#

if you are open to dependencies, you could use once_cell

dusky root
#

Thank you, but I'll take your advice and just use a simple array for now, since I don't expect that the array will ever grow to larger than 100 elements.

autumn shoal
#

?play

use once_cell::sync::Lazy;
use std::collections::HashSet;

static FRUITS: Lazy<HashSet<&'static str>> = Lazy::new(|| HashSet::from(["apple", "banana"]));

fn is_fruit(thing: &str) -> bool {
    FRUITS.contains(thing)
}
marsh spokeBOT
tough tundra