To convert a set of strings to a set of floats in Rust, you can use the parse()
method along with the collect()
method to transform each string value into its corresponding float value.
In this example,
string_vec1
with values vec!["1.1", "2.2", "3.3"]
.parse()
method on each string element of string_vec1
to parse it into a float value.collect()
method to collect the parsed float values into a HashSet
named float_set1
.use std::collections::HashSet;
fn main() {
let string_vec1 = vec!["1.1", "2.2", "3.3"];
let float_set1: HashSet<f64> = string_vec1
.iter()
.map(|s| s.parse::<f64>().unwrap())
.collect();
println!("{:?}", float_set1);
}
{"1.1", "2.2", "3.3"}
In this example,
string_vec2
with values vec!["4.5", "5.6", "6.7"]
.parse()
method on each string element of string_vec2
to parse it into a float value.collect()
method to collect the parsed float values into a HashSet
named float_set2
.use std::collections::HashSet;
fn main() {
let string_vec2 = vec!["4.5", "5.6", "6.7"];
let float_set2: HashSet<f64> = string_vec2
.iter()
.map(|s| s.parse::<f64>().unwrap())
.collect();
println!("{:?}", float_set2);
}
{"4.5", "5.6", "6.7"}
In this tutorial, we learned How to Convert a Set of Strings to a Set of Floats in Rust language with well detailed examples.