In Rust, you can convert a set of strings to a set of integers using the parse() method.
In this example,
use std::collections::HashSet;
fn main() {
let string_set1: HashSet<&str> = ["1", "2", "3", "4", "5"].iter().cloned().collect();
let mut int_set1 = HashSet::new();
for str in string_set1.iter() {
if let Ok(num) = str.parse::<i32>() {
int_set1.insert(num);
}
}
for num in int_set1.iter() {
println!("{}", num);
}
}
1 2 3 4 5
In this example,
use std::collections::HashSet;
use std::str::FromStr;
fn main() {
let string_set2: HashSet<&str> = ["10", "20", "30", "40", "50"].iter().cloned().collect();
let mut int_set2 = HashSet::new();
for str in string_set2.iter() {
if let Ok(num) = i32::from_str(str) {
int_set2.insert(num);
}
}
for num in int_set2.iter() {
println!("{}", num);
}
}
10 20 30 40 50
In this tutorial, we learned How to Convert a Set of Strings to a Set of Integers in Rust language with well detailed examples.