title: How to convert Rust strings to UTF-16?
body: <blockquote>
    <p>Editor's note: This code example is from a version of Rust prior to 1.0 and is not valid Rust 1.0 code, but the answers still contain valuable information.</p>
  </blockquote>
  
  <p>I want to pass a string literal to a Windows API. Many Windows functions use UTF-16 as the string encoding while Rust's native strings are UTF-8. </p>
  
  <p>I know Rust has <a href="https://doc.rust-lang.org/0.12.0/std/str/trait.StrSlice.html#tymethod.utf16_units" rel="noreferrer">utf16_units()</a> to produce a UTF-16 character iterator, but I don't know how to use that function to produce a UTF-16 string with zero as last character.</p>
  
  <p>I'm producing the UTF-16 string like this, but I am sure there is a better method to produce it:</p>
  
  <pre><code>extern "system" {
      pub fn MessageBoxW(hWnd: int, lpText: *const u16, lpCaption: *const u16, uType: uint) -&gt; int;
  }
  
  pub fn main() {
      let s1 = [
          'H' as u16, 'e' as u16, 'l' as u16, 'l' as u16, 'o' as u16, 0 as u16,
      ];
      unsafe {
          MessageBoxW(0, s1.as_ptr(), 0 as *const u16, 0);
      }
  }
  </code></pre>