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.
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
Asked: 2021-11-08 11:00:00 +0000
Seen: 9 times
Last updated: Aug 10 '22
What are the Cordapp Certificates used for in terms of signing and interacting?
How can SSL be used with CqlSessionFactoryBean in Springboot Cassandra?
How to set up Database First configuration in Entity Framework 7 for MVC 6?
How can I address the issue of Content Security Policy blocking more than I had anticipated?
How do I resolve a 502 error when attempting to call an HTTPS REST API from an HTTP REST API?
What does borrowing or moving a value from `stdout` mean?