rust record struct with exclusive fields

  Kiến thức lập trình

tl;dr how do I create a record struct with mutually exclusive fields?

I have a record struct. I’m using the records procmacro to make this a bit easier.

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!"),
    }
}

I would like the match statement to not need a panic or have any other error handling. Or in other words, there should never be a MyRecord where both fields are Some(_) or both fields are None.

I would like to do something like this (contrived code):

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: _ } => {},
    }
}

How would I do something similar to that code? exclusive_record_struct is a made-up example procmacro. However, it does not need to be procmacro. The most important thing is having a record struct that can guarantee only one field is set.

I know I could use a union. However, a union does not provide this guarantee, nor does a union know which fields are valid.

1

LEAVE A COMMENT