作者:捕鱼达人2502856571 | 来源:互联网 | 2022-12-18 10:23
鉴于以下计划:
use std::collections::HashMap;
fn main() {
let mut hm = HashMap::new();
hm.insert(0, 1);
hm.insert(1, 1);
let mut iter = hm.iter();
println!("{:?}", iter.nth(0).expect("Fatal.").0)
}
我为代码的每次执行运行获得了不同的输出:
procyclinsur@procyclinsur:~/Documents/Rust/t1$ cargo run
Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs
Running `target/debug/t1`
1
procyclinsur@procyclinsur:~/Documents/Rust/t1$ vim src/main.rs
procyclinsur@procyclinsur:~/Documents/Rust/t1$ cargo run
Compiling t1 v0.1.0 (file:///home/procyclinsur/Documents/Rust/t1)
Finished dev [unoptimized + debuginfo] target(s) in 1.12 secs
Running `target/debug/t1`
1
procyclinsur@procyclinsur:~/Documents/Rust/t1$ cargo run
Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs
Running `target/debug/t1`
1
procyclinsur@procyclinsur:~/Documents/Rust/t1$ cargo run
Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs
Running `target/debug/t1`
0
procyclinsur@procyclinsur:~/Documents/Rust/t1$ cargo run
Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs
Running `target/debug/t1`
1
我希望每次运行程序都能看到相同的输出.有谁知道这个代码以这种方式表现的原因?如何让它按预期输出0?
1> ljedrz..:
这是因为a HashMap
是无序的.它的iter
方法
以任意顺序访问所有键值对
有关集合的文档描述了这种行为:
对于像HashMap这样的无序集合,项目将以内部表示最方便的顺序产生.
为了始终检索特定值,您需要按键搜索(或使用不依赖于顺序的Iterator
方法之一,例如find
); 例如:
use std::collections::HashMap;
fn main() {
let mut hm = HashMap::new();
hm.insert(0, "a");
hm.insert(1, "b");
println!("{:?}", hm.get(&0)) // always Some("a")
}