title: How can I deserialize an optional field with custom functions using Serde?
body: <p>I want to serialize and deserialize a <code>chrono::NaiveDate</code> with custom functions, but the Serde book does not cover this functionality and the code docs also do not help.</p>
  
  <pre><code>#[macro_use]
  extern crate serde_derive;
  extern crate serde;
  extern crate serde_json;
  extern crate chrono;
  
  use chrono::NaiveDate;
  
  
  mod date_serde {
      use chrono::NaiveDate;
      use serde::{self, Deserialize, Serializer, Deserializer};
  
      pub fn serialize&lt;S&gt;(date: &amp;Option&lt;NaiveDate&gt;, s: S) -&gt; Result&lt;S::Ok, S::Error&gt;
      where S: Serializer {
          if let Some(ref d) = *date {
              return s.serialize_str(&amp;d.format("%Y-%m-%d").to_string())
          }
          s.serialize_none()
      }
  
      pub fn deserialize&lt;'de, D&gt;(deserializer: D)
          -&gt; Result&lt;Option&lt;NaiveDate&gt;, D::Error&gt;
          where D: Deserializer&lt;'de&gt; {
          let s: Option&lt;String&gt; = Option::deserialize(deserializer)?;
          if let Some(s) = s {
              return Ok(Some(NaiveDate::parse_from_str(&amp;s, "%Y-%m-%d").map_err(serde::de::Error::custom)?))
          }
  
          Ok(None)
      }
  }
  
  #[derive(Debug, Serialize, Deserialize)]
  struct Test {
      pub i: u64,
      #[serde(with = "date_serde")]
      pub date: Option&lt;NaiveDate&gt;,
  }
  
  fn main() {
      let mut test: Test = serde_json::from_str(r#"{"i": 3, "date": "2015-02-03"}"#).unwrap();
      assert_eq!(test.i, 3);
      assert_eq!(test.date, Some(NaiveDate::from_ymd(2015, 02, 03)));
      test = serde_json::from_str(r#"{"i": 5}"#).unwrap();
      assert_eq!(test.i, 5);
      assert_eq!(test.date, None);
  }
  </code></pre>
  
  <p>I know that <code>Option&lt;chrono::NaiveDate&gt;</code> can be easily deserialized by Serde because Chrono has Serde support, <strong>but</strong> I'm trying to learn Serde so I want to implement it myself. When I run this code I have a error:</p>
  
  <pre class="lang-none prettyprint-override"><code>thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: ErrorImpl { code: Message("missing field `date`"), line: 1, column: 8 }', /checkout/src/libcore/result.rs:859
  note: Run with `RUST_BACKTRACE=1` for a backtrace.
  </code></pre>