sunface / rust-by-practice

Learning Rust By Practice, narrowing the gap between beginner and skilled-dev through challenging examples, exercises and projects.
https://practice.course.rs
Creative Commons Attribution 4.0 International
12.22k stars 985 forks source link

集合类型-hashmap 第二题答案有误 #500

Open dggrok opened 8 months ago

dggrok commented 8 months ago

hashmap 章节第二题 答案如下

use std::collections::HashMap;

fn main() {
    let teams = [
        ("Chinese Team", 100),
        ("American Team", 10),
        ("France Team", 50),
    ];

    let mut teams_map1 = HashMap::new();
    for team in &teams {
        teams_map1.insert(team.0, team.1);
    }

    let teams_map2: HashMap<_,_> = teams.into_iter().collect();

    assert_eq!(teams_map1, teams_map2);

    println!("Success!")
}

运行会报错如下:

error[E0277]: a value of type `HashMap<_, _>` cannot be built from an iterator over elements of type `&(&str, {integer})`
    --> main.rs:15:54
     |
15   |     let teams_map2: HashMap<_,_> = teams.into_iter().collect();
     |                                                      ^^^^^^^ value of type `HashMap<_, _>` cannot be built from `std::iter::Iterator<Item=&(&str, {integer})>`
     |
     = help: the trait `FromIterator<&(&str, {integer})>` is not implemented for `HashMap<_, _>`
     = help: the trait `FromIterator<(_, _)>` is implemented for `HashMap<_, _>`
     = help: for that trait implementation, expected `(_, _)`, found `&(&str, {integer})`
note: the method call chain might not have had the expected associated types
    --> main.rs:15:42
     |
4    |       let teams = [
     |  _________________-
5    | |         ("Chinese Team", 100),
6    | |         ("American Team", 10),
7    | |         ("France Team", 50),
8    | |     ];
     | |_____- this expression has type `[(&str, {integer}); 3]`
...
15   |       let teams_map2: HashMap<_,_> = teams.into_iter().collect();
     |                                            ^^^^^^^^^^^ `Iterator::Item` is `&(&str, {integer})` here
note: required by a bound in `collect`
    --> /Users/yaw/.rustup/toolchains/stable-aarch64-apple-darwin/lib/rustlib/src/rust/library/core/src/iter/traits/iterator.rs:2050:19
     |
2050 |     fn collect<B: FromIterator<Self::Item>>(self) -> B
     |                   ^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `Iterator::collect`

error: aborting due to previous error

For more information about this error, try `rustc --explain E0277`.

正确解答应该terms 用 vec 定义,如下:

use std::collections::HashMap;

fn main() {
    let teams = vec![
        ("Chinese Team", 100),
        ("American Team", 10),
        ("France Team", 50),
    ];

    let mut teams_map1 = HashMap::new();
    for team in &teams {
        teams_map1.insert(team.0, team.1);
    }

    let teams_map2: HashMap<_,_> = teams.into_iter().collect();

    assert_eq!(teams_map1, teams_map2);

    println!("Success!")
}
dggrok commented 8 months ago

补充本人版本 1.75 WX20240223-182948@2x