Updated June 1, 2023
Definition of Rust Set
Rust set is a very important data structure of rust programming language and helps in identifying the key present in the set which possess the required element. Sets in rust programming language mostly revolve around the keys, not the values, as mostly the key associated with the element is enough to retrieve the information about any element. Sets can perform various operations like union, difference, symmetric difference, and intersection on the available data, which programmers mostly adopt. HashSet and BTreeSet, which are important in Rust, make up the majority of sets.
Syntax:
The syntax flow for Rust Set is as follows :
use std::collections : : HashSet;
let mut var_0 = HashSet : : new ();
var_0.insert("some_val");
{
Logic to be implemented
}
Functional calls ;
Where,
HashSet is imported as part of the standard library and collections in Rust, followed by a conventional variable where the provisioning for insertion of elements is done using the new keyword, and then the value is created to implement the logic and to perform further functional calls from the set comprising of elements.
How set works in Rust?
- Working of set in Rust is used and performed for various operations and activities that make this data structure quite useful in terms of adaptation by programmers.
- Sets in Rust have the unique feature of wrapping the keys and mapping appropriately, which guarantees not to possess duplicate elements.
- Hash set and B-tree Set are part of the sets in Rust which is also part of the hashmap whose values are not much important, but keys present play a crucial role.
- If two keys present are equal, then their hashes will also be the same or equal it should not be unique in nature.
- If, in a scenario, some logic error happens, then in that case, the eq and the hash values present might get differ and will create a lot of commotion in terms of execution; thus, it is important to keep in mind the equality trait or hash trait to determine properly while it is present in that set.
- The scenario mentioned so far arises only in case of un-equal code or by following wrong practices when implementing the code in a rust programming language.
- If the hash implementation differs for a given key, it can lead to a panic, causing the contents within the hash set to become corrupted and potentially useless. In such cases, it may be necessary to drop or remove the affected elements.
- You can create a HashSet by initializing and implementing a fixed list of elements from the defined arrays.
- To display and perform operations such as symmetric difference, difference, union, and intersection on the elements present in the array, you will need to import the hashbrown and HashSet modules from the standard collection.
- The standard inbuild library comprising of HashSet needs to be imported initially to perform any operation related to Sets and keys with associated values; otherwise, the execution will not be proper and might get distorted, thus throwing exceptions and errors.
- Some inbuild hash functions, like a hash drain and hash brown, and many others, need version compatibility. Each version’s standard collection might get different or the library might have been deprecated.
- Programmers often adopt sets to enhance computational power by utilizing operations such as union, intersection, difference, and symmetry. These operations enable efficient and speedy manipulation of sets.
Examples
Let us discuss examples of Rust Set.
Example #1
This program demonstrates the Rust hash set, which demonstrates the union operation by inserting the elements and representing them as shown in the output.
Code:
use std::collections::HashSet;
fn main()
{
let mut x: HashSet<i32> = vec![3i32, 4, 5].into_iter().collect();
let mut y: HashSet<i32> = vec![4i32, 5, 6].into_iter().collect();
assert!(x.insert(6));
assert!(y.contains(&6));
y.insert(7);
println!("X: {:?}", x);
println!("Y: {:?}", y);
println!("Perform_Union_Operation: {:?}", x.union(&y).collect::<Vec<&i32>>());
}
Output:
Example #2
In this program, we demonstrate the use of hash sets in Rust. We calculate the differences between two sets and display the results in the output below.
Code:
use std::collections::HashSet;
fn main() {
let mut x: HashSet<i32> = vec![3i32, 4, 5].into_iter().collect();
let mut y: HashSet<i32> = vec![4i32, 5, 6].into_iter().collect();
assert!(x.insert(6));
assert!(y.contains(&6));
y.insert(7);
println!("X: {:?}", x);
println!("Y: {:?}", y);
println!("Difference_in_both: {:?}", x.difference(&y).collect::<Vec<&i32>>());
}
Output:
Example #3
This program demonstrates the representation of a fixed set of elements which in this case is fruits from the set of defined arrays as shown in the output.
Code:
use std::collections::HashSet;
fn main() {
let fruits: HashSet<&'static str> =
[ "apple", "kiwi", "Mango", "Guava" ].iter().cloned().collect();
for x_0 in &fruits {
println!("{:?}", x_0);
}
}
Output:
Example #4
This program showcases a hash set where the elements contained within the hash set named “set_08” are iterated and printed in an arbitrary order, as displayed in the output.
Code:
use std::collections::HashSet;
fn main()
{
let mut set_08: HashSet<_> = [8, 9, 10].iter().cloned().collect();
assert!(!set_08.is_empty());
for i_0 in set_08.drain() {
println!("{}", i_0);
}
assert!(set_08.is_empty());
}
Output:
Example #5
This program showcases the Rust set by measuring the number of elements, inserting elements, and asserting their equality.
Code:
use std::collections::HashSet;
fn main()
{
let mut v_l_0 = HashSet::new();
assert_eq!(v_l_0.len(), 0);
v_l_0.insert(1);
assert_eq!(v_l_0.len(), 1);
println!("{:?}", v_l_0);
}
Output:
Conclusion
Most programmers have embraced Rust as a programming language following the emergence of the C language. Rust’s data structure capabilities have introduced increased flexibility and adaptability, enabling the execution of various operations and manipulations. It makes Rust programming interesting and enhances learning and skill development due to its versatile nature.
Recommended Articles
We hope that this EDUCBA information on “Rust Set” was beneficial to you. You can view EDUCBA’s recommended articles for more information.