title: Expand tilde in Rust Path idiomatically
body: <p>Sometimes, for instance when reading some configuration file, you read a file path entered by the user without going through the shell (for instance, you get <code>~/test</code>).</p>
  
  <p>As <code>Option 2</code> below doesn’t write to test file in user home directory, I’m wondering if there is something more idiomatic than <code>Option 1</code>.</p>
  
  <pre class="lang-rust prettyprint-override"><code>use std::env::var;
  use std::fs::File;
  use std::io::prelude::*;
  use std::path::Path;
  
  fn write_to(path: &amp;Path) {
      let mut f = File::create(path).unwrap();
      f.write_all("Hi".as_bytes()).unwrap();
  }
  
  fn main() {
      // Option 1
      let from_env = format!("{}/test", var("HOME").unwrap());
      let with_var = Path::new(&amp;from_env);
      // Create $HOME/test
      write_to(with_var);
  
      // Option 2
      let with_tilde = Path::new("~/test");
      // Create the test file in current directory, provided a directory ./~ exists
      write_to(with_tilde);
  }
  </code></pre>
  
  <p><strong><em>Note</strong>: <code>unwrap()</code> is used here to keep the example short. There should be some error handling in production code.</em></p>