Storing from inside a loop a borrowed value to container in outer scope?

后端 未结 2 1476
情歌与酒
情歌与酒 2020-12-11 19:07

I set myself a little task to acquire some basic Rust knowledge. The task was:

Read some key-value pairs from stdin and put them into a hashmap.

2条回答
  •  [愿得一人]
    2020-12-11 20:00

    In Rust 1.1 the function words was marked as deprecated. Now you should use split_whitespace.

    Here is an alternative solution which is a bit more functional and idiomatic (works with 1.3).

    use std::io::{self, BufRead};
    use std::collections::HashMap;
    
    fn main() {
        let stdin = io::stdin();
    
        // iterate over all lines, "change" the lines and collect into `HashMap`
        let map: HashMap<_, _> = stdin.lock().lines().filter_map(|line_res| {
            // convert `Result` to `Option` and map the `Some`-value to a pair of
            // `String`s
            line_res.ok().map(|line| {
                let kv: Vec<_> = line.split_whitespace().take(2).collect();
                (kv[0].to_owned(), kv[1].to_owned())
            })
        }).collect();
    
        println!("{}", map.len());
    }
    

提交回复
热议问题