Search code examples
rusthashmap

Use &[u8] as key in HashMap


How can I fix this function:

fn func<'a>(x: &'a HashMap<&[u8], String>) -> Option<&'a String> {
    let k = vec![1, 2, 3];
    let k: &[u8] = &k;
    x.get(&k)
}

I receive error

error[E0515]: cannot return value referencing local variable `k`
 --> src/lib.rs:6:5
  |
5 |     let k: &[u8] = &k;
  |                    -- `k` is borrowed here
6 |     x.get(&k)
  |     ^^^^^^^^^ returns a value referencing data owned by the current function

Solution

  • Why it happens is complicated, but the fix is simple:

    fn func<'a>(x: &'a HashMap<&[u8], String>) -> Option<&'a String> {
        let k = vec![1, 2, 3];
        let k: &[u8] = &k;
        x.get(k)
    }
    

    Note the removed &.