0

I am trying to make an iterator that maps a string to an integer:

fn main() {
    use std::collections::HashMap;

    let mut word_map = HashMap::new();

    word_map.insert("world!", 0u32);

    let sentence: Vec<&str> = vec!["Hello", "world!"];

    let int_sentence: Vec<u32> = sentence.into_iter()
        .map(|x| word_map.entry(x).or_insert(word_map.len() as u32))
        .collect();

}

(Rust playground)

This fails with

the trait core::iter::FromIterator<&mut u32> is not implemented for the type collections::vec::Vec<u32>

Adding a dereference operator around the word_map.entry().or_insert() expression does not work as it complains about borrowing which is surprising to me as I'm just trying to copy the value.

4

1 回答 1

3

借用检查器使用词法生存期规则,因此在单个表达式中不能有冲突的借用。解决方案是将获取长度提取到单独的let语句中:

let int_sentence: Vec<u32> = sentence.into_iter()
        .map(|x| *({let len = word_map.len() as u32;
                    word_map.entry(x).or_insert(len)}))
        .collect();

当 Rust 支持非词法生命周期时,这些问题有望消失。

于 2016-05-16T06:48:01.687 回答