In Rust, you can convert a set of integers to a set of strings by mapping each integer to its string representation using the to_string()
method.
In this example,
int_set
.iter()
method to create an iterator over the elements of int_set
.map()
method along with the to_string()
method to convert each integer element to its string representation.collect()
method.use std::collections::HashSet;
fn main() {
// Set of integers
let int_set: HashSet<i32> = [1, 2, 3, 4, 5].iter().cloned().collect();
// Convert set of integers to set of strings
let string_set: HashSet<String> = int_set.iter()
.map(|x| x.to_string())
.collect();
// Print the set of strings
for s in &string_set {
println!("{}", s);
}
}
1 2 3 4 5
In this example,
empty_set
.use std::collections::HashSet;
fn main() {
// Empty set of integers
let empty_set: HashSet<i32> = HashSet::new();
// Convert empty set to set of strings
let empty_string_set: HashSet<String> = empty_set.iter()
.map(|x| x.to_string())
.collect();
// Print the empty set of strings (will be empty)
for s in &empty_string_set {
println!("{}", s);
}
}
In this tutorial, we learned How to Convert a Set of Integers to a Set of Strings in Rust language with well detailed examples.