HashSet en Rust — principiantes

Leo Gutiérrez
2 min readApr 23, 2024

En Rust, un HashSet es una colección o una estructura de datos que almacena elementos de manera única sin un orden en particular. HashSet garantiza que puedes recuperar o validar si un elemento se encuentra en la colección de manera eficiente: O(1)

Creando un HashSet

Para crear un HashSet, necesitas incluír el tipo desde el módulo std::collections:

use std::collections::HashSet;

fn main() {
let s1 = HashSet::new();
}

Como ya sabes, el compilador infiere los tipos, pero podemos ser más explícitos y especificar el tipo a la hora de crearlo:

let s1: HashSet<i32>= HashSet::new();

Podemos inicializar un HashSet usando un array:

let some_values = [1, 2, 3, 4];
let unique_numbers: HashSet<i32> = HashSet::from(some_values);
let unique_numbers2: HashSet<i32> = HashSet::from([1, 3, 2, 3, 4, 5]);

Este es un ejemplo completo y usando into():

use std::collections::HashSet;

fn main() {
let some_values = [1, 2, 3, 4];
let unique_numbers: HashSet<i32> = HashSet::from(some_values);
let unique_numbers2: HashSet<i32> = HashSet::from([1, 3, 2, 3, 4, 5]);
let unique_numbers3: HashSet<i32> = [1, 3, 2, 3, 4, 5].into();

println!("unique_numbers = {:?}", unique_numbers);
println!("unique_numbers2 = {:?}", unique_numbers2);
println!("unique_numbers3 = {:?}", unique_numbers3);
}

--

--

Leo Gutiérrez

Hi! I am Leonardo Gutiérrez R., a passionate software developer, I hope you find the content in this blog interesting. I write about IT related stuff.