简体   繁体   English

Rust HashMap find_or_insert

[英]Rust HashMap find_or_insert

Why does HashMap.find_or_insert(k,v) return a &mut type, and how do it get it to return a type ? 为什么HashMap.find_or_insert(k,v)返回一个&mut类型,以及如何使它返回一个type

I just started using Rust for a course, and I am using a HashMap<int, int> and want to get an int back. 我刚开始在课程中使用Rust,而我正在使用HashMap<int, int>并想找回一个int

let mut m: HashMap<int, int> = HashMap::new();
println!("{:d}", m.find_or_insert(1,2));

gives me an error saying that it failed to find an implementation of trait std::fnt::Signed for &mut int . 给我一个错误,说它failed to find an implementation of trait std::fnt::Signed for &mut int


Edit1: EDIT1:

I am using Rust 0.9 on Windows 8.1, using msys. 我正在Windows 8.1上使用msys使用Rust 0.9。

My code so far 到目前为止我的代码

use std::hashmap::HashMap;

fn main() {
    let mut m: HashMap<int, int> = HashMap::new();
    println!("{:d}", *m.find_or_insert(1,2))
}

I tried this code again and it properly returns 2 我再次尝试了此代码,它正确返回2

Why does find_or_insert return a reference? 为什么find_or_insert返回引用? Copying isn't always possible/efficient. 复制并非总是可能/有效的。

How can you use that reference in the case of an integer? 如果是整数,如何使用该引用? Dereference it with a * : *取消引用:

let mut m: HashMap<int, int> = HashMap::new();
println!("{:d}", *m.find_or_insert(1,2));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM