[Rust] Collect()

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));

 

posted @   Zhentiw  阅读(69)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2019-05-15 [Functional Programming] Week logic
2018-05-15 [Javascript] Getter and Setter Abstractions
2017-05-15 [Recompose] Flatten a Prop using Recompose
2017-05-15 [Recompose] Lock Props using Recompose -- withProps
2017-05-15 [Recompose] Transform Props using Recompose --mapProps
2017-05-15 [Recompose] Add Lifecycle Hooks to a Functional Stateless Component using Recompose
2016-05-15 [PWA] 4. Hijacking Request
点击右上角即可分享
微信分享提示