为什么此Rust 2018代码使用“货物构建”而不使用rustc进行编译?

时间:2019-03-09 22:14:11

标签: rust borrow-checker

在使用货运方式编译以下代码段时,借阅检查器似乎正常,但是在使用rustc时出现错误

error[E0502]: cannot borrow `char_counts` as mutable because it is also borrowed as immutable
  --> src/lib.rs:14:17
   |
10 |         let count = char_counts.get(&char);
   |                     ----------- immutable borrow occurs here
...
14 |                 char_counts.insert(char, rem);
   |                 ^^^^^^^^^^^ mutable borrow occurs here
...
19 |     }
   |     - immutable borrow ends here

为什么会发生这种情况?

use std::collections::HashMap;

pub fn anagram(word: &str, another_word: &str) -> i32 {
    let mut char_counts = HashMap::new();
    for char in word.chars() {
        let count = char_counts.entry(char).or_insert(0);
        *count += 1;
    }
    for char in another_word.chars() {
        let count = char_counts.get(&char);
        if let Some(val) = count {
            let rem = val - 1;
            if rem > 0 {
                char_counts.insert(char, rem);
            } else {
                char_counts.remove(&char);
            }
        }
    }
    println!("{:?}", char_counts);
    return char_counts.keys().len() as i32;
}

cargo --versionrustc --version命令都输出1.33

1 个答案:

答案 0 :(得分:5)

如果启用了non-lexical lifetimes,则此函数可以正常编译,并且没有它们就无法编译。默认情况下,2018版启用它们。也许您的edition = "2018"中有Cargo.toml,但是在直接使用rustc时没有将其作为参数传递吗?