Home > OS >  Check Some, None in multiple nested enums at once
Check Some, None in multiple nested enums at once

Time:09-30

I am looking for a way to use a functional event-type mechanism in my project. Nothing is in production yet, so this can even be rewritten from scratch:

I want to look for 2 things:

  • Presence of value (Option<T>)
  • Functional treatment of different types, for determinism

I've done the latter, but I have some issues with the first one: For requests that look like this:

POST http://127.0.0.1:8000/publish_event HTTP/1.1
content-type: application/json

{
    "source_id": "user:asdf",
    "key": "temperature",
    "value": 25
}

I've set up the following structs and enums:

    use std::option::{Option};
    use serde::{Deserialize};
    
    #[derive(Deserialize, Debug)]
    pub struct EventPayload<T>{
        pub key: String,
        pub tag: Option<String>,
        pub value: Option<T>
    }
    
    #[derive(Deserialize, Debug)]
    #[serde(untagged)]
    pub enum EventValue {
        String(EventPayload<String>),
        Float(EventPayload<f32>),
        Int(EventPayload<i32>),
        Bool(EventPayload<bool>)
    }
    
    #[derive(Deserialize, Debug)]
    pub struct PublishSingleValueEventRequest {
        pub source_id: String,
        #[serde(flatten)]
        pub manifest: EventValue
    }

And then, I am using rocket for a simple endpoint. This is where problems appear:

#[macro_use] extern crate rocket;
use rocket::serde::json::Json;
use rocket::http::Status;

#[post("/publish_event", format="application/json", data="<request>")]
pub fn publish_event(request: Json<PublishSingleValueEventRequest>) -> Status {
    let event = request.0;
    
    /* This region does not compile
    let evt_val: Option = match event.manifest {
        EventValue::String(x) => x.value,
        EventValue::Float(x) => x.value,
        EventValue::Int(x) => x.value,
        EventValue::Bool(x) => x.value
    };

    match evt_val {
        Some(x) => println!("Event value: {:?}", x),
        None => println!("No event value provided")
    }
    */


    println!("{:?}", event.manifest);
    match event.manifest {
        EventValue::String(x) => {
            println!("String payload: {:?}", x.value);
        }

        EventValue::Float(x) => {
            println!("Float payload: {:?}", x.value);
        }

        EventValue::Int(x) => {
            println!("Int payload: {:?}", x.value);
        }
        
        EventValue::Bool(x) => {
            println!("Bool payload: {:?}", x.value);
        }
    }

    Status::Accepted
}

#[launch]
fn rocket() -> _ {
    rocket::build().mount("/", routes![publish_event])
}

I would also like this to be more like

match event.manifest.value {
    Some(x) => ...,
    None => ...
}

...instead of manually unwrapping the .value Option<> fields.

CodePudding user response:

The real question here is: what do you really want to do with evt_val? If all you want is to display it, then you can map to an Option<&dyn Debug>:

let evt_val: Option::<&dyn Debug> = match event.manifest {
    EventValue::String(x) => x.value.as_ref().map (|v| v as &dyn Debug),
    EventValue::Float(x) => x.value.as_ref().map (|v| v as &dyn Debug),
    EventValue::Int(x) => x.value.as_ref().map (|v| v as &dyn Debug),
    EventValue::Bool(x) => x.value.as_ref().map (|v| v as &dyn Debug),
};

match evt_val {
    Some(x) => println!("Event value: {:?}", x),
    None => println!("No event value provided")
}

CodePudding user response:

You can pattern match nested structurues:

fn main() {
    let payload: EventPayload<i32> = EventPayload {
        key: "foo".to_string(),
        tag: None,
        value: Some(10),
    };
    let value = EventValue::Int(payload);
    
    match value {
        EventValue::Int(EventPayload {value: Some(x), ..}) => {
            println!("Some value: {}", x);
        }
        EventValue::String(EventPayload {value: Some(message), ..}) => {
            println!("Some message: {}", message);
        }
        _ => {
            println!("whatever");
        }
    }
}

Playground

  • Related