Reduce boilerplate in API by internalizing &str -> String
authorJacob Casper <dev@jacobcasper.com>
Mon, 19 Oct 2020 19:22:33 +0000 (14:22 -0500)
committerJacob Casper <dev@jacobcasper.com>
Mon, 19 Oct 2020 19:22:33 +0000 (14:22 -0500)
String is required for thread safety but it's cumbersome to call like
that. Pass in literals and convert as necessary.

src/main.rs

index fd92244..0a5eda3 100644 (file)
@@ -5,10 +5,10 @@ use std::collections::HashMap;
 use std::sync::{Arc, Mutex};
 use std::time::Duration;
 
-fn update_map(arc_map: Arc<Mutex<HashMap<String, String>>>, key: String, val: String) {
+fn update_map(arc_map: Arc<Mutex<HashMap<String, String>>>, key: &str, val: &str) {
     let clone_arc = arc_map.clone();
     let mut map = clone_arc.lock().unwrap();
-    map.insert(key, val.clone());
+    map.insert(String::from(key), String::from(val));
     for (k, v) in &*map {
         println! {"{}: {}", k.clone(), v.clone()};
     }
@@ -42,20 +42,12 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
                                 // Variant holding a variant that should just be a Vec<&str> I
                                 // believe. This is _the recommended_ way to do this by the author.
                                 let inner_value = value?.as_iter()?.next()?.as_iter()?.next()?;
-                                let artist = String::from(inner_value.as_str()?);
-                                update_map(
-                                    arc_locked_xset_map,
-                                    String::from("artist"),
-                                    String::from(artist),
-                                );
+                                let artist = inner_value.as_str()?;
+                                update_map(arc_locked_xset_map, "artist", artist);
                             }
                             "xesam:title" => {
                                 let title = value?.as_iter()?.next()?.as_str()?;
-                                update_map(
-                                    arc_locked_xset_map,
-                                    String::from("title"),
-                                    String::from(title),
-                                );
+                                update_map(arc_locked_xset_map, "title", title);
                             }
                             _ => (),
                         }