String collect: automaticlly calling concat on string
let foo: String = vec!["this", "is", "a", "test"]
.into_iter()
.collect();
println!("{:?}", foo); // thisisatest
HashSet:
let foo: HashSet<isize> = vec![1, 2, 3]
.into_iter()
.collect();
HashMap:
use std::collections::HashMap;
fn main() {
let foo: HashMap<&str, usize> = vec!["this", "is", "a", "test"]
.into_iter()
.enumerate()
.map(|(idx, item)| (item, idx))
.collect();
println!("{:?}", foo); // {"this": 0, "is": 1, "a": 2, "test": 3}
}
Number:
let value: usize = vev![1,2,3]
.iter()
.sum(); // 6
let how_many_items: usize = vec![1,2,3]
.iter()
.skip(2)
.count(); // 1
vec![1,2,5,9,4]
.iter()
.skip(2)
.take_while(|&x| x > 4)
.for_each(|&x| println!("{}", x)) // 5, 9
let what_about_this: usize = vec![1, 2, 3]
.iter()
.filter(|x| *x % 2 == 0)
.count() // 1
In Rust, the .iter()
method on a Vec<T>
creates an iterator over immutable references to the elements of the vector. Therefore, in the context of your filter function, x
is of type &i32
, not i32
.
The *
operator is used to dereference x
to get the value it points to. Without it, you'd be trying to perform the modulus operation on a reference (&i32
), not the integer value (i32
) itself. The Rust compiler will not automatically dereference the value for you in this context, so you need to use the *
operator to explicitly dereference it.
let map = HashMap::from([
("foo", 1),
("bar", 2),
("baz", 3),
]);
map
.iter()
.for_each(|(k, v)| println!("{}: {}", k, v));
let set = HashSet::from([
"foo",
"bar",
"baz",
]);
set
.iter()
.for_each(|v| println!("{}", v));
标签:i32,iter,Collect,let,vec,println,foo,Rust From: https://www.cnblogs.com/Answer1215/p/17401931.html