Ask Your Question
1

How can a struct be transformed into a key value pair only for fields that are not "none" in Rust?

asked 2021-11-08 11:00:00 +0000

ladyg gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2022-08-10 02:00:00 +0000

lalupa gravatar image

One way to transform a struct into a key-value pair for non-"none" fields in Rust is by implementing the From trait for the struct. This allows us to specify how to transform the struct into another type, in this case a HashMap<String, String>.

Here's an example implementation:

use std::collections::HashMap;

#[derive(Debug)]
struct MyStruct {
    field1: Option<String>,
    field2: Option<String>,
    field3: Option<String>,
}

impl From<MyStruct> for HashMap<String, String> {
    fn from(s: MyStruct) -> HashMap<String, String> {
        let mut map = HashMap::new();
        if let Some(value) = s.field1 {
            map.insert(String::from("field1"), value);
        }
        if let Some(value) = s.field2 {
            map.insert(String::from("field2"), value);
        }
        if let Some(value) = s.field3 {
            map.insert(String::from("field3"), value);
        }
        map
    }
}

fn main() {
    let my_struct = MyStruct {
        field1: Some(String::from("hello")),
        field2: None,
        field3: Some(String::from("world")),
    };
    let key_value_map: HashMap<String, String> = my_struct.into();
    println!("{:?}", key_value_map); // prints: {"field1": "hello", "field3": "world"}
}

In this example, we define a struct MyStruct with three fields that are all Option<String>. We implement From for the struct, which creates a HashMap<String, String> from the struct.

In the implementation of From, we create a new empty HashMap. For each non-"none" field in the struct, we insert a new key-value pair into the HashMap with the field name as the key (represented as a String) and the field value as the value (also represented as a String). Finally, we return the HashMap.

In the main() function, we create an instance of MyStruct with two fields that are non-"none". We then call the into() method on the struct to transform it into a HashMap<String, String>. Finally, we print the resulting map using println!(). The output shows the keys and values of the HashMap, which correspond to the non-"none" fields of the original struct.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-11-08 11:00:00 +0000

Seen: 9 times

Last updated: Aug 10 '22