【发布时间】:2023-01-17 04:32:07
【问题描述】:
我正在尝试序列化一个枚举。我计划通过首先对枚举的序数进行编码,然后对与 enum to bytes / bytes to enum? 非常相似的值进行序列化。这个问题的答案涉及使用一个板条箱,serde;我想避免使用这个板条箱。
似乎有两种类型的枚举:有数据和没有数据,它们在某些方面是不兼容的。使用 as u8 似乎可以从没有数据的枚举中获取序数值,非常简单。一个值从 as u8 返回带有数据的枚举变体,但是没有数据的枚举变体(当其他枚举变体有数据时)无法编译:
https://play.rust-lang.org/?gist=2f6a4e8507a59d451546a69407bc0d77
#[repr(u8)]
enum Enumeration {
One=0,
}
#[repr(u8)]
enum Other {
Twelve(String)=4,
Thirteen=5,
}
fn main() {
println!("Got unsigned {:?}", Enumeration::One as u8);
println!("Got other {:?}", Other::Twelve as u8);
// Uncommenting the next line produces a compiler error
//println!("Got other {:?}", Other::Thirteen as u8);
}
(我的印象是从带有数据的枚举变体返回的值没有用。)
如何获取带有数据的枚举变体的序数?
【问题讨论】:
-
你没有得到
Twelve的判别式。 -
@ChayimFriedman 没错。在阅读“鉴于 rustc 保证
#[repr(u16)]枚举以其判别式存储为u16...”(github.com/rust-lang/rfcs/pull/2363/files)开始后,我感到有些惊讶。