Rust converting a struct to key value pair where the field is not none

762 Views Asked by At

I have a struct generated by prost (protobuf implementation based on proto).

pub struct Data {
    #[prost(string, tag="1")]
    pub field1: ::prost::alloc::string::String,
    #[prost(message, optional, tag="2")]
    pub struct_2: ::core::option::Option<Struct2>,
    #[prost(message, optional, tag="3")]
    pub struct_3: ::core::option::Option<Struct3>,
    #[prost(string, tag="4")]
    pub test_param: ::prost::alloc::string::String,
}

I am able to decode the protobuf data from the above.

The catch is I receive some fields which are none in the above struct. only some fields are filled at any given time.

eg:

Data { field1: "testfield", struct_2: None, struct_3: None, test_param: "test" }

I want to be able to:

  1. select only non-none values from the struct.
  2. Iterate over them and put them as a key value pair.

Eg:

let keyvalue = Hashmap::new()
for k,v in buffered_data.to_vector().iter() {
  if k.IsSome(){
    keyvalue.insert("k",v)   
  }
}

expected output would be something like:

keyvalue:
{
"field1":"test_field",
"test_param": "test"
}
0

There are 0 best solutions below