Primitive Type str
Unicode string manipulation (str type)
Basic Usage
Rust's string type is one of the core primitive types of the language. While
represented by the name str, the name str is not actually a valid type in
Rust. Each string must also be decorated with a pointer. String is used
for an owned string, so there is only one commonly-used str type in Rust:
&str.
&str is the borrowed string type. This type of string can only be created
from other strings, unless it is a static string (see below). As the word
"borrowed" implies, this type of string is owned elsewhere, and this string
cannot be moved out of.
As an example, here's some code that uses a string.
fn main() { let borrowed_string = "This string is borrowed with the 'static lifetime"; }fn main() { let borrowed_string = "This string is borrowed with the 'static lifetime"; }
From the example above, you can see that Rust's string literals have the
'static lifetime. This is akin to C's concept of a static string.
String literals are allocated statically in the rodata of the
executable/library. The string then has the type &'static str meaning that
the string is valid for the 'static lifetime, otherwise known as the
lifetime of the entire program. As can be inferred from the type, these static
strings are not mutable.
Mutability
Many languages have immutable strings by default, and Rust has a particular
flavor on this idea. As with the rest of Rust types, strings are immutable by
default. If a string is declared as mut, however, it may be mutated. This
works the same way as the rest of Rust's type system in the sense that if
there's a mutable reference to a string, there may only be one mutable reference
to that string. With these guarantees, strings can easily transition between
being mutable/immutable with the same benefits of having mutable strings in
other languages.
Representation
Rust's string type, str, is a sequence of unicode codepoints encoded as a
stream of UTF-8 bytes. All safely-created strings are guaranteed to be validly
encoded UTF-8 sequences. Additionally, strings are not null-terminated
and can contain null codepoints.
The actual representation of strings have direct mappings to vectors: &str
is the same as &[u8].
Trait Implementations
impl<'a> AsciiCast<&'a [Ascii]> for &'a str
unsafe fn to_ascii_nocheck(&self) -> &'a [Ascii]
fn is_ascii(&self) -> bool
fn to_ascii(&self) -> T
fn to_ascii_opt(&self) -> Option<T>
impl<'a> StrAsciiExt for &'a str
fn to_ascii_upper(&self) -> String
fn to_ascii_lower(&self) -> String
fn eq_ignore_ascii_case(&self, other: &str) -> bool
impl<'a> Clone for &'a str
fn clone<'a>(&self) -> &'a str
Return a shallow copy of the slice.