AddAssign for u64

Hi Folks,

I am learning Rust, and attempting to create a simple program which counts phrases from a file (sample code below). This AddAssign operation works fine if I attempt the example, but I am missing something with regards to ownership when I attempt to loop through the contents of the text.

From what I can gather, u64 does implement AddAssign, so I’m not sure what I am missing here. Any guidance is greatly appreciated.

Error: error[E0368]: binary assignment operation+=cannot be applied to type&u64``

use std::collections::HashMap;
use std::io::prelude::*;
use std::io::{self, BufReader};

fn main() -> io::Result<()> {
    let f = "This is a file with a newline.\nThis is a file without much in it.".as_bytes();
    let f = BufReader::new(f);
    let mut phraseMap = HashMap::new();

    for line in f.lines() {
        let v: Vec<String> = line.unwrap()
            .split_whitespace()
            .map(|s| s.to_string())
            .collect();
        let len = v.len();
        let i = 0;
        while i + 2 < len {
            let count = phraseMap.entry(&v[i..i + 3].join(" ")).or_insert(&0);
            *count += 1;
            i = i + 1;

        }
    }

    Ok(())
}

You didn’t specify the generic K and V types of your map, so they are inferred from use. hash_map::Entry::or_insert takes a direct V, which you gave &0, so it’s inferred that V = &{integer} (with the exact integer type still to be determined, but will default to i32). Same for the key, HashMap::entry takes a direct K, inferred from what you gave to be K = &String.

So you’ll end up with a HashMap<&String, &i32> here, when you wanted HashMap<String, u64>.

The real issue is with the arg to entry - it should be a String, not &String, and then or_insert() can take 0, not &0 - playground

In the code you had, you were getting back a &mut &u64 as the value (since &0 was used as the value), which is of course not what you want (and it doesn’t implement AddAssign).

1 Like

Thanks for the clarification @vitalyd!. I was attempting many of these combinations, but missed something.