我想在内存中表示一个数据表,如下所示:
| USD | EUR |
-----+-----+-----+
John | 100 | 50 |
-----+-----+-----+
Tom | 300 | 200 |
-----+-----+-----+
Nick | 200 | 0 |
-----+-----+-----+
有一组已知的人,他们每个人都拥有一些货币。
我有以下枚举:
enum Person {
John,
Tom,
Nick
}
enum Currency {
USD,
EUR
}
我想将此数据编码为 2D 数组,如果能够不是通过
usize
而是通过 enum
来索引数组元素,那就太酷了。例如:
data[Person::John][Currency::USD] = 100;
Rust 中可以使用数组和枚举吗?或者还有其他数据结构可以用于此目的吗?
我知道
HashMap
,但这并不完全是我想要的,因为:
HashMap
在堆上工作(这使得它比常规堆栈分配数组慢得多)HashMap
不能保证该项目存在。例如。每次我想要得到一些东西时,我都必须打开它并处理None
的情况,与普通数组的使用相比,这不是很方便。这与如何将枚举值与整数匹配?不同,因为我对将枚举转换为
usize
不感兴趣;我只是想要一种通过枚举访问数组/映射项的便捷方法。
ljedrz 提供了一个很好的解决方案。 解决该问题的另一种方法是使用现有的板条箱enum-map。
将以下内容添加到您的
Cargo.toml
:
[dependencies]
enum-map = "*"
enum-map-derive = "*"
然后,在
src/main.rs
:
extern crate enum_map;
#[macro_use] extern crate enum_map_derive;
#[derive(Debug, EnumMap)]
enum Person { John, Tom, Nick }
#[derive(Debug, EnumMap)]
enum Currency { USD, EUR }
use enum_map::EnumMap;
use Person::*;
use Currency::*;
fn main() {
// Create 2D EnumMap populated with f64::default(), which is 0.0
let mut table : EnumMap<Person, EnumMap<Currency, f64>> = EnumMap::default();
table[John][EUR] = 15.25;
println!("table = {:?}", table);
println!("table[John][EUR] = {:?}", table[John][EUR]);
}
输出:
table = EnumMap { array: [EnumMap { array: [0, 15.25] }, EnumMap { array: [0, 0] }, EnumMap { array: [0, 0] }] }
table[John][EUR] = 15.25
如果您需要使用数组来实现,这并不像看起来那么简单。
为了能够将这两条信息包含在一个数组中(以便能够通过它们进行索引),您首先需要将它们组合成一个类型,例如在结构中:
struct Money([(Currency, usize); 2]);
struct PersonFinances {
person: Person,
money: Money
}
然后,如果您希望能够对表进行索引,则需要将其包装在您自己的类型中,以便您可以为其实现
Index
特征:
use std::ops::Index;
struct Table([PersonFinances; 3]);
impl Index<(Person, Currency)> for Table {
type Output = usize;
fn index(&self, idx: (Person, Currency)) -> &Self::Output {
&self
.0
.iter()
.find(|&pf| pf.person == idx.0) // find the given Person
.expect("given Person not found!")
.money
.0
.iter()
.find(|&m| m.0 == idx.1) // find the given Currency
.expect("given Currency not found!")
.1
}
}
然后您可以通过
Table
、Person
对来索引 Currency
:
table[(Tom, EUR)]
这并不像看上去那么难。我很欣赏你说你“对将 enum 转换为 usize 不感兴趣”,但人们可能会误解你,认为你想不惜一切代价避免这种情况。您在这里所要做的就是:
data[Person::John as usize][Currency::USD as usize] = 100;
只要
data
确实是一个二维数组,所有内容都会编译,不会出现警告或错误,并且会按预期工作。
实际上,您可能需要在第一个元素上添加“= 0”来声明 Person,如下所示:
enum Person { John = 0, Dave, Dan, Will }
我喜欢用这个作弊:
enum Person { John = 0, Dave, SIZE }
enum Currency { USD = 0, CAD, SIZE }
let mut my2d: [[f32; Person::SIZE as usize]; Currency::SIZE as usize] = [[0., 0.], [0., 0.]];
my2d[Person::John as usize][Currency::USD as usize] = 5.4;
println!("$$: {}", my2d[Person::John as usize][Currency::USD as usize]);
HashMap
:
use std::collections::HashMap;
#[derive(PartialEq, Eq, Hash)]
enum Person {
John,
Tom,
Nick
}
#[derive(PartialEq, Eq, Hash)]
enum Currency {
USD,
EUR
}
type Table = HashMap<Person, HashMap<Currency, f32>>;
fn main() {
let mut table = Table::new();
let mut currency = HashMap::<Currency, f32>::new();
currency.insert(Currency::USD, 100_f32);
table.insert(Person::John, currency);
println!("{}", table[&Person::John][&Currency::USD]);
}