1 | initial version |
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.