Skip to content

Instantly share code, notes, and snippets.

@bb010g
Last active July 12, 2017 12:42
Show Gist options
  • Save bb010g/f4db7c179c589ebdc08a1753885c4080 to your computer and use it in GitHub Desktop.
Save bb010g/f4db7c179c589ebdc08a1753885c4080 to your computer and use it in GitHub Desktop.
Rust String vs &str

I get why String vs &str is a thing beginners struggle with, but it's never an issue in actual code, at least more than Vec<T> vs &[T] is. &[T] is a slice of borrowed memory. Vec<T> is owned memory. String and &str talk about verified UTF-8 strings. String -> Vec<u8>. &str -> &[u8]. Use in exactly the same way you would your normal hunk of memory types.

Beyond that, when you want to get a slice of your vector, you use &vec. When you want to get a &str out of your String, use &string. When you want to copy a slice into a new vector, you use Vec::from(slice). When you want to copy a &str into a new String, you use String::from(str).

When you want the raw u8s out of a String or &str, use str.as_bytes() or string.into_bytes(). When you want to put raw u8s into a String or &str, use str::from_utf8(slice) or String::from_utf8(vec).

Refer to the docs for methods present on String and &str that aren't on vectors and slices.

There you go! No magic, just owned vs. borrowed memory, put in separate types because strings are kinda important.

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