Skip to content

Instantly share code, notes, and snippets.

@algesten
Last active December 8, 2016 14:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save algesten/c4d5d5683a4bc58333b3230f9b6918fb to your computer and use it in GitHub Desktop.
Save algesten/c4d5d5683a4bc58333b3230f9b6918fb to your computer and use it in GitHub Desktop.

Rust type conversions String, &str, Vec and &[u8]

From &str

  • &str -> String has many equally valid methods: String::from(st), st.to_string(), st.to_owned().
    • But I suggest you stick with one of them within a single project. The major advantage of String::from is that you can use it as an argument to a map method. So instead of x.map(|s| String::from(s)) you can often use x.map(String::from).
  • &str -> &[u8] is done by st.as_bytes()
  • &str -> Vec<u8> is a combination of &str -> &[u8] -> Vec<u8>, i.e. st.as_bytes().to_owned()

From String

  • String -> &str should just be &s where coercion is available or s.as_str() where it is not.
  • String -> &[u8] is the same as &str -> &[u8]: s.as_bytes()
  • String -> Vec<u8> has a custom method: s.into_bytes()

From &[u8]

  • &[u8] -> Vec<u8> is done by u.to_owned()
  • &[u8] -> &str doesn't actually exist, that would be &[u8] -> Result<&str, Error>, provided via str::from_utf8(u)
  • &[u8] -> String is the combination of &[u8] -> Result<&str, Error> -> Result<String, Error>

From Vec<u8>

  • Vec<u8> -> &[u8] should be just &v where coercion is available, or as_slice where it's not.
  • Vec<u8> -> &str is the same as Vec<u8> -> &[u8] -> Result<&str, Error>: str::from_utf8(&v)
  • Vec<u8> -> String doesn't actually exist, that would be Vec<u8> -> Result<String, Error> via String::from_utf8(v)

Coercion is available whenever the target is not generic but explicitly typed as &str or &[u8] respectively

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment