rust - 为什么这个 Rust 2018 代码使用 `cargo build` 编译但不使用 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
解决方案
如果您启用了非词法生命周期并且没有它们将无法编译,则此函数将编译得很好。2018 版默认启用它们。也许您edition = "2018"
在rustc 中有Cargo.toml
,但在直接使用 rustc 时没有将其作为参数传递?
推荐阅读
- python - Multiple Locations for Python Packages
- php - 如何允许具有“作者”角色的用户发布用户定义类型的记录,并且只有作者才能阅读记录?
- mongodb - $in 需要一个数组作为第二个参数
- python - PyQt 无法正确显示像素图
- javascript - 您如何在 firebase 中创建另一个唯一的用户 ID?
- reactjs - React 路由器不能 GET 任何指定的路由,除了根 /
- html - Webview 在 Kotlin 中不显示某些图像
- python - 如何使用集合差异比较熊猫数据帧
- android - 在应用 android 代码架构/设计模式时遇到问题
- visual-studio-code - 如何在 Visual Studio Code 中为所有用户禁用遥测?