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 u8
s out of a String
or &str
, use
str.as_bytes()
or
string.into_bytes()
.
When you want to put raw u8
s 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.