Conjuntos (std::set)
En esta página
Set garantiza que cada elemento aparezca como máximo una vez. Importe con
use std::Set. La API cubre creación, inserción, eliminación, pruebas de pertenencia y
las operaciones algebraicas de conjunto — unión e intersección.
Crear y agregar
Set::new() crea un conjunto vacío. add ignora silenciosamente los valores
duplicados. has prueba pertenencia en O(1).
Deduplicación automática de cadenas y enteros; patrón de filtrado de duplicados en bucle.
// Feature: Set.new / Set.add / Set.has — create and populate a set
// When to use: enforcing uniqueness, fast membership tests.
use std::Set
let s = Set::new()
s.add("a")
s.add("b")
s.add("a") // duplicate: ignored
print(s.len()) // expected: 2
print(s.has("a")) // expected: true
print(s.has("c")) // expected: false
// Set with integers.
let nums = Set::new()
nums.add(1)
nums.add(2)
nums.add(3)
nums.add(2) // dup
print(nums.len()) // expected: 3
// Pattern: filter duplicates in a loop.
let raw = ["foo", "bar", "foo", "baz", "bar", "qux"]
let uniq = Set::new()
for w in raw {
uniq.add(w)
}
print(uniq.len()) // expected: 4
Eliminar y verificar tamaño
remove(v) elimina el elemento — operar en un elemento inexistente es seguro.
is_empty() es el atajo para len() == 0.
is_empty antes y después de inserciones; remove idempotente; vaciado incremental.
// Feature: Set.remove / Set.len / Set.is_empty
// When to use: clearing entries dynamically, checking for an empty set.
use std::Set
let s = Set.new()
print(s.is_empty()) // expected: true
print(s.len()) // expected: 0
s.add("a")
s.add("b")
s.add("c")
print(s.is_empty()) // expected: false
print(s.len()) // expected: 3
s.remove("b")
print(s.has("b")) // expected: false
print(s.len()) // expected: 2
// remove on a missing key is safe.
s.remove("z")
print(s.len()) // expected: 2
// Empty it out.
s.remove("a")
s.remove("c")
print(s.is_empty()) // expected: true
Unión e intersección
union devuelve un nuevo conjunto con todos los elementos de ambos; intersect
devuelve solo los elementos comunes. Set::from(array) es el constructor a partir
de un array.
Etiquetas compartidas entre dos posts via intersect; union para combinar dos conjuntos.
// Feature: Set.union / Set.intersect — set operations
// When to use: combining tag lists, finding common elements.
use std::Set
let a = Set::from([1, 2, 3])
let b = Set::from([2, 3, 4])
// Union — every element in A or B.
let u = a.union(b)
print(u.len()) // expected: 4
print(u.has(1)) // expected: true
print(u.has(4)) // expected: true
// Intersection — only elements in both A and B.
let i = a.intersect(b)
print(i.len()) // expected: 2
print(i.has(2)) // expected: true
print(i.has(3)) // expected: true
print(i.has(1)) // expected: false
// Practical case: tags shared between two posts.
let tags1 = Set::from(["rust", "zolo", "compilers"])
let tags2 = Set::from(["zolo", "vm", "compilers"])
let common = tags1.intersect(tags2)
print(common.len()) // expected: 2
print(common.has("zolo")) // expected: true
print(common.has("compilers")) // expected: true
Convertir a array
Set::from(array) deduplica al construir; to_array() extrae los elementos de
vuelta. Componer ambos es el idioma estándar para deduplicar una lista.
Set::from + to_array para deduplicar; union + to_array para fusionar dos listas sin repetición.
// Feature: Set.from / Set.to_array — converting between Set and array
// When to use: deduplicating an array, then iterating or serializing the result.
use std::Set
// from — creates a set from an array, deduplicating.
let s = Set::from([1, 2, 2, 3, 3, 3, 4])
print(s.len()) // expected: 4
// to_array — extracts the elements as an array.
let arr = s.to_array()
print(arr.len()) // expected: 4
// Classic pattern: deduplicate a list of strings.
let raw = ["foo", "bar", "foo", "baz", "bar"]
let unique = Set::from(raw).to_array()
print(unique.len()) // expected: 3
// Combine union + to_array to merge two lists without duplicates.
let l1 = ["red", "green"]
let l2 = ["green", "blue"]
let merged = Set::from(l1).union(Set::from(l2)).to_array()
print(merged.len()) // expected: 3
Desafío
Dado un array de palabras con repeticiones, use Set::from para obtener las únicas,
convierta a array con to_array, ordene manualmente (con reduce o sort
si está disponible) e imprima en orden.
Consulta también