簡體   English   中英

為什么此Rust 2018代碼使用`cargo build`編譯但不使用rustc編譯?

[英]Why does this Rust 2018 code compile with `cargo build` but not using rustc?

在使用cargo build編譯以下代碼段時,借用檢查器似乎很好,但是在使用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

如果啟用了非詞性生存期 ,則此函數可以正常編譯,並且如果沒有它們,就無法編譯。 默認情況下,2018版啟用它們。 也許您在Cargo.toml具有edition = "2018" ,但是在直接使用rustc時沒有將其作為參數傳遞嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM