我有代码():
use std::collections::HashMap;
// We have some arbitrary struct (given values just placeholders)
struct SomeStruct {
x: f32,
y: usize,
}
fn main() {
// We have some hashmap which contains the names (keys) and properties (values) of items.
// These are known at compile time.
let hashmap: HashMap<&str, SomeStruct> = vec![
("a", SomeStruct { x: 2., y: 2 }),
("b", SomeStruct { x: 3.5, y: 1 }),
("c", SomeStruct { x: 0., y: 5 }),
]
.into_iter()
.collect();
// We then have a bunch of data which arbitrarily references the names of these items.
// This data is also known at compile time.
}
不断打字"a"
,"b"
等需要引用的项目是不好的。
可以使用枚举来改善这一点,例如:
enum Items {
A = SomeStruct { x: 2., y: 2 },
B = SomeStruct { x: 3.5, y: 1 },
C = SomeStruct { x: 0., y: 5 },
}
这实际上是一个const
枚举,这样当将来引用这些项目时我们可以简单地这样做Items::A
or &Items::A
而不是'a'
并且必须进行必要的哈希处理。
看来这样做是行不通的。
有没有办法使用const enum
?或者有其他更好的解决方案吗?
虽然这个问题可能是重复的如何在 Rust 中创建具有常量值的枚举? https://stackoverflow.com/questions/36928569/how-can-i-create-enums-with-constant-values-in-rust使用任意结构时,该问题下提出的解决方案不起作用。这添加了瓦伦丁溶液 https://stackoverflow.com/a/62759540/155423确实如此,但这个解决方案确实更适用于其他解决方案不起作用的情况。我认为它在这个问题的背景下提供了一个更好更清晰的答案,而其他更简单的解决方案不起作用。