Info
This post is auto-generated from RSS feed The Rust Programming Language Forum - Latest topics. Source: What is the best way to convert a Vec<(String, String)> into a struct
I'm currently writing a web application that uses diesel for database interaction. I have one table for global settings with two columns, one for the setting and the other the value. This gets serialized by diesel into a Vec<(String, String)>
.
The problem is that I somehow have to convert the Vec<(String, String)>
into a single Settings
struct. Currently this is done by converting the vector into an iterator, convert the iterator into a hashmap and use the hashmap to construct Settings
:
use std::collections::HashMap;
fn main() {
// Settings are queried from the database here
let settings: Vec<(String, String)> = vec![("setting1".to_string(), "value1".to_string()), ("setting3".to_string(), "value3".to_string())];
let mut settings: HashMap<String, String> = settings.into_iter().collect();
let settings = Settings {
setting1: settings.remove("setting1").unwrap_or_else(|| "defaultvalue1".to_string()),
setting2: settings.remove("setting2").unwrap_or_else(|| "defaultvalue2".to_string()),
setting3: settings.remove("setting3").unwrap_or_else(|| "defaultvalue3".to_string()),
};
assert_eq!(
settings,
Settings {
setting1: "value1".to_string(),
setting2: "defaultvalue2".to_string(),
setting3: "value3".to_string(),
}
);
}
#[derive(Debug ,PartialEq)]
struct Settings {
setting1: String,
setting2: String,
setting3: String,
}
However, this feels like it isn't the best way of doing this. Are there better/more efficient ways of doing this?
EDIT:
I do know that the default hasher of HashMap is slow, I just used it in this example for the sake of simplicity.
2 posts - 2 participants
🏷️ Rust_feed