tl;dr如何创建具有互斥字段的记录结构?
我有一个记录结构。我正在使用records
procmacro 来使这变得更容易一些。
use ::records;
#[records::record]
pub struct MyRecord {
a: Option<bool>,
b: Option<i32>,
}
fn main() {
let mr: MyRecord = MyRecord::new(/* either field might be Some(..), but not both*/);
match mr {
MyRecord { a: Some(_), b: None } => {},
MyRecord { a: None, b: Some(_) } => {},
_ => panic!("bad MyRecord!"),
}
}
我希望该match
语句不需要panic
或有任何其他错误处理。或者换句话说,永远不应该有一个MyRecord
where 两个字段都为Some(_)
或两个字段都为None
。
我想做这样的事情(人为的代码):
use ::exclusive_record_struct;
#[exclusive_record_struct]
pub struct MyRecord {
a: bool,
b: i32,
}
fn main() {
let mr: MyRecord = MyRecord::new(/* either field might be set, but not both*/);
match mr {
MyRecord { a: _ } => {},
MyRecord { b: _ } => {},
}
}
我将如何做类似该代码的事情?exclusive_record_struct
是一个虚构的 procmacro 示例。然而,它不需要是 procmacro。最重要的是拥有一个可以保证只设置一个字段的记录结构。
我知道我可以使用union
. 然而,aunion
不提供这种保证,也不知道union
哪些字段是有效的。
在 Rust 中,您可以将数据附加到枚举的变体,如下所示:
请参阅:https://doc.rust-lang.org/book/ch06-01-defining-an-enum.html#enum-values