为什么这个 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 --version
和 rustc --version
命令都输出 1.33
如果您启用了 non-lexical lifetimes,此函数将编译正常,没有它们将无法编译。 2018 版默认启用它们。也许您的 Cargo.toml
中有 edition = "2018"
,但在直接使用 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 --version
和 rustc --version
命令都输出 1.33
如果您启用了 non-lexical lifetimes,此函数将编译正常,没有它们将无法编译。 2018 版默认启用它们。也许您的 Cargo.toml
中有 edition = "2018"
,但在直接使用 rustc 时没有将其作为参数传递?