是否可以定义一个枚举而不用担心Rust中的内存分配?
假设以下是我的枚举的定义。
pub enum Orientation {
North,
South,
East,
West,
}
我想知道是否可以在代码中引用sayt_code的相同实例。
以下代码是否会生成
Orientation::North
的两个单独的实例?let o1 = Orientation::North;
let o2 = Orientation::North;
我知道我可以通过定义如下的静态变量来实现。
有没有更好的方法(在语法上更安全/更简单/更干净)来完成相同的事情?
pub enum Orientation {
North,
South,
East,
West,
}
static NORTH: Orientation = Orientation::North;
static SOUTH: Orientation = Orientation::South;
static WEST: Orientation = Orientation::West;
static EAST: Orientation = Orientation::East;
最佳答案
您在运行时询问的代码与您编写的代码相同:
let o1: u8 = 0;
let o2: u8 = 0;
枚举可让您抽象出实际发生的情况,以便您同时获得效率和语法上的便利,并在忘记匹配项中的变体时获得类型检查和错误。
创建静态“常量”将不会有任何结果,因为传递字节是您已经可以做的最快的事情。
Is there a better (syntactically safer/simpler/cleaner) way to do the same thing?
使用枚举的“最佳”方法是最简单的方法:
let o1 = Orientation::North;
let o2 = Orientation::North;
关于enums - Rust中的静态枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62450750/