title: How do you make a Serde struct work with both borrowed and owned data?
body: <p>I want to make a Serde struct that is capable of being deserialized from either borrowed data (<code>serde_json::from_str</code>) or owned data (<code>serde_json::from_reader</code>).  I have read <a href="https://serde.rs/lifetimes.html" rel="noreferrer">Understanding deserializer lifetimes</a>, and I understand the difference between the two trait bounds (<code>&lt;'de, T&gt; where T: Deserialize&lt;'de&gt;</code> and <code>&lt;T&gt; where T: DeserializeOwned</code>); what I want is a struct that implements both trait bounds, such that it can be used from either deserialization function.</p>
  <p>The following code (<a href="https://play.rust-lang.org/?version=stable&amp;mode=debug&amp;edition=2018&amp;gist=979338e8ba8c46602b6d1a52bb5223d4" rel="noreferrer">playground</a>) refuses to compile:</p>
  <pre class="lang-rust prettyprint-override"><code>use serde_json; // 1.0.56
  use serde; // 1.0.114
  use std::fs;
  use std::io;
  use std::borrow::Cow;
  
  #[derive(serde::Deserialize)]
  struct Resource&lt;'s&gt; {
      // The Cow should allow for either borrowed or owned data
      #[serde(borrow)]
      pub foo: Cow&lt;'s, str&gt;,
  }
  
  fn main() {
      {
          // Works as expected when referencing a string...
          let s = &quot;{\&quot;foo\&quot;:\&quot;bar\&quot;}&quot;;
          let resource: Resource = serde_json::from_str(s).unwrap();
      }
      {
          // ...but refuses to compile when reading from a file
          let file = fs::File::open(&quot;dummy.json&quot;).unwrap();
          let reader = io::BufReader::new(file);
          let resource: Resource = serde_json::from_reader(reader).unwrap();
      }
  }
  </code></pre>
  <p>How do I make this struct work with both owned and borrowed data?  Is there a way to do something like <code>#[serde(borrow_optional)]</code>?</p>