indexing - Rust: 不能使用 HashMap::
问题描述
我有一个名为 Point 的结构元组。它是一个二维笛卡尔坐标。我需要使用一个点作为哈希图中的键,但编译器拒绝。我该如何处理?
#[derive(PartialEq, Eq, Hash, Copy, Clone, Debug)]
struct Point(i16, i16);
const ROOT: Point = Point(0,0);
let mut visited = std::collections::HashMap::<Point,bool>::new();
visited[&ROOT] = true;
编译器错误如下:
error[E0594]: cannot assign to data in an index of `std::collections::HashMap<Point, bool>`
--> src/main.rs:124:3
|
124 | visited[&ROOT] = true;
| ^^^^^^^^^^^^^^^^^^^^^ cannot assign
|
= help: trait `IndexMut` is required to modify indexed content, but it is not implemented for `std::collections::HashMap<Point, bool>`
解决方案
HashMap
不执行IndexMut
。条目的突变通过get_mut()
借用的密钥或通过entry()
API 与拥有的密钥进行。
在您的情况下,get_mut()
将返回,None
因为您没有在地图中插入任何内容。visited.insert(ROOT, true)
会为你做的。
推荐阅读
- java - 卡夫卡流 - 按价值属性分组?
- r - 为什么这个闪亮的应用程序会给出“只能从反应式表达式内部完成”的错误
- python - 从字符串表示构造 QueryDict
- powershell - 如何在 Powershell 中从这个类似 Hashtable 的文本中提取值?
- node.js - Nodejs Typescript 仅类型包未正确导出所有类型
- r - 按间隔和条件对数据进行分组
- powershell - 在 Azure Devops 的计划中执行 exe
- arrays - TypeError:赋值的右侧不能在数组映射上解构
- javascript - 使用 Service Worker 时检测在线状态不起作用
- javascript - 如何使用谷歌地理编码 API 从地址获取纬度和经度?