You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
use std::collections::HashMap;fnmain(){let teams = [("Chinese Team",100),("American Team",10),("France Team",50),];letmut 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;fnmain(){let teams = vec![("Chinese Team", 100),
("American Team", 10),
("France Team", 50),
];letmut 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!")}
The text was updated successfully, but these errors were encountered:
hashmap 章节第二题
答案如下
运行会报错如下:
正确解答应该terms 用 vec 定义,如下:
The text was updated successfully, but these errors were encountered: