rust 使用&[u8]作为HashMap中的键

r8xiu3jd  于 11个月前  发布在  其他
关注(0)|答案(2)|浏览(124)

如何修复此功能:

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

字符串
我收到错误

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

xwmevbvl

xwmevbvl1#

  • 为什么 * 它发生是复杂的,但解决方法很简单:
fn func<'a>(x: &'a HashMap<&[u8], String>) -> Option<&'a String> {
    let k = vec![1, 2, 3];
    let k: &[u8] = &k;
    x.get(k)
}

字符串
注意删除的&

lf3rwulv

lf3rwulv2#

k的简化版本,没有第二个语句:

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

字符串
Playground

相关问题