In Rust, you can use a HashSet to store a collection of unique strings.
In this example,
string_set
to store unique strings.insert
method.use std::collections::HashSet;
fn main() {
// Create a HashSet for strings
let mut string_set = HashSet::new();
// Add strings to the HashSet
string_set.insert("Apple".to_string());
string_set.insert("Banana".to_string());
string_set.insert("Cherry".to_string());
// Print the HashSet
println!("{:?}", string_set);
}
{"Cherry", "Banana", "Apple"}
In this example,
contains
method to check if a specific string exists in the HashSet.contains
method returns true if the string is in the HashSet, otherwise false.// Check if the HashSet contains a string
let contains_banana = string_set.contains("Banana");
println!("HashSet contains Banana: {}", contains_banana);
In this tutorial, we learned How to create a Set of Strings in Rust language with well detailed examples.