title: Best way to deserialize a key=value list of strings in Rust
body: <p>I have multiple structs that need to be deserialized from a String that is a bunch of lines with key value pairs which represent the struct's attributes.</p>
  
  <p>Example</p>
  
  <pre><code>field1=something
  field2=556
  field3=true
  field4=10.0.0.1
  </code></pre>
  
  <p>The types for each field will always be the same, but are not always present. The order can also change.</p>
  
  <pre><code>struct Data {
      field1: Option&lt;String&gt;,
      field2: Option&lt;u32&gt;,
      field3: Option&lt;bool&gt;,
      field4: Option&lt;std::net::Ipv4Addr&gt;
  }
  </code></pre>
  
  <p>What is the best way to do this? Should I be using the <code>serde</code> crate?</p>
  
  <p>I know that I can do it manually like this (see <a href="https://play.rust-lang.org/?version=stable&amp;mode=debug&amp;edition=2018&amp;gist=e16244e50492aa218217cb44d5f27cfe" rel="nofollow noreferrer">https://play.rust-lang.org/?version=stable&amp;mode=debug&amp;edition=2018&amp;gist=e16244e50492aa218217cb44d5f27cfe</a>)</p>
  
  <p>But how do I genericise this for multiple structs?</p>
  
  <pre><code>use std::net::Ipv4Addr;
  use std::str::FromStr;
  
  #[derive(Debug)]
  struct Data {
      field1: Option&lt;String&gt;,
      field2: Option&lt;u32&gt;,
      field3: Option&lt;bool&gt;,
      field4: Option&lt;Ipv4Addr&gt;,
  }
  
  fn main() {
      let mut s = "field1=something
  field2=556
  field3=true
  field4=10.0.0.1"
          .to_string();
  
      let mut field1 = None;
      let mut field2 = None;
      let mut field3 = None;
      let mut field4 = None;
  
      let lines: Vec&lt;_&gt; = s.split("\n").collect();
  
      for line in lines {
          let pair: Vec&lt;_&gt; = line.splitn(2, "=").collect();
          let key = pair[0];
          let value = pair[1];
  
          match key {
              "field1" =&gt; {
                  field1 = Some(value.to_owned());
              }
              "field2" =&gt; {
                  field2 = Some(u32::from_str(value).unwrap());
              }
              "field3" =&gt; {
                  field3 = match value {
                      "true" =&gt; Some(true),
                      "false" =&gt; Some(false),
                      _ =&gt; None
                  };
              }
              "field4" =&gt; {
                  field4 = Some(Ipv4Addr::from_str(value).unwrap());
              }
              _ =&gt; {}
          }
      }
  
      println!(
          "{:?}",
          Data {
              field1,
              field2,
              field3,
              field4
          }
      );
  }
  </code></pre>