String vs &str
String
Owned by the variable, meaning the variable controls the memory.
Can be mutated.
Ideal for strings whose size can change or need to persist beyond the scope of their original reference.
&str
Borrowed, immutable string slice.
Represents a view into a string, rather than owning the data.
Usually refers to a segment of a String or a string literal.
Immutable by default.
Conversions Between String and &str
Convert &str to String: Use the to_string or String::from methods.
Convert String to &str: Borrow a string using & or .as_str().
Examples
In above example the
x.trim
function will work because it doesn't manipulate the string.Instead it return a slice of original string.
But
x + "world"
got compile error because you cannot mutate the variablex: &str
.
Above example will work because
x
is converted toString
and can be mutated.In other words, any function or method that manipulate the value will not work using
&str
but will work usingString
type.
References
Last updated