Primitive Type str
Expand description
String slices.
The str type, also called a ‘string slice’, is the most primitive string
type. It is usually seen in its borrowed form, &str. It is also the type
of string literals, &'static str.
§Basic Usage
String literals are string slices:
Here we have declared a string slice initialized with a string literal.
String literals have a static lifetime, which means the string hello_world
is guaranteed to be valid for the duration of the entire program.
We can explicitly specify hello_world’s lifetime as well:
§Representation
A &str is made up of two components: a pointer to some bytes, and a
length. You can look at these with the as_ptr and len methods:
use std::slice;
use std::str;
let story = "Once upon a time...";
let ptr = story.as_ptr();
let len = story.len();
// story has nineteen bytes
assert_eq!(19, len);
// We can re-build a str out of ptr and len. This is all unsafe because
// we are responsible for making sure the two components are valid:
let s = unsafe {
// First, we build a &[u8]...
let slice = slice::from_raw_parts(ptr, len);
// ... and then convert that slice into a string slice
str::from_utf8(slice)
};
assert_eq!(s, Ok(story));Note: This example shows the internals of &str. unsafe should not be
used to get a string slice under normal circumstances. Use as_str
instead.
§Invariant
Rust libraries may assume that string slices are always valid UTF-8.
Constructing a non-UTF-8 string slice is not immediate undefined behavior, but any function called on a string slice may assume that it is valid UTF-8, which means that a non-UTF-8 string slice can lead to undefined behavior down the road.
Implementations§
Source§impl str
impl str
1.0.0 (const: 1.39.0) · Sourcepub const fn is_empty(&self) -> bool
pub const fn is_empty(&self) -> bool
Returns true if self has a length of zero bytes.
§Examples
1.87.0 (const: 1.87.0) · Sourcepub const fn from_utf8(v: &[u8]) -> Result<&str, Utf8Error>
pub const fn from_utf8(v: &[u8]) -> Result<&str, Utf8Error>
Converts a slice of bytes to a string slice.
A string slice (&str) is made of bytes (u8), and a byte slice
(&[u8]) is made of bytes, so this function converts between
the two. Not all byte slices are valid string slices, however: &str requires
that it is valid UTF-8. from_utf8() checks to ensure that the bytes are valid
UTF-8, and then does the conversion.
If you are sure that the byte slice is valid UTF-8, and you don’t want to
incur the overhead of the validity check, there is an unsafe version of
this function, from_utf8_unchecked, which has the same
behavior but skips the check.
If you need a String instead of a &str, consider
String::from_utf8.
Because you can stack-allocate a [u8; N], and you can take a
&[u8] of it, this function is one way to have a
stack-allocated string. There is an example of this in the
examples section below.
§Errors
Returns Err if the slice is not UTF-8 with a description as to why the
provided slice is not UTF-8.
§Examples
Basic usage:
// some bytes, in a vector
let sparkle_heart = vec![240, 159, 146, 150];
// We can use the ? (try) operator to check if the bytes are valid
let sparkle_heart = str::from_utf8(&sparkle_heart)?;
assert_eq!("💖", sparkle_heart);Incorrect bytes:
// some invalid bytes, in a vector
let sparkle_heart = vec![0, 159, 146, 150];
assert!(str::from_utf8(&sparkle_heart).is_err());See the docs for Utf8Error for more details on the kinds of
errors that can be returned.
A “stack allocated string”:
1.87.0 (const: 1.87.0) · Sourcepub const fn from_utf8_mut(v: &mut [u8]) -> Result<&mut str, Utf8Error>
pub const fn from_utf8_mut(v: &mut [u8]) -> Result<&mut str, Utf8Error>
Converts a mutable slice of bytes to a mutable string slice.
§Examples
Basic usage:
// "Hello, Rust!" as a mutable vector
let mut hellorust = vec![72, 101, 108, 108, 111, 44, 32, 82, 117, 115, 116, 33];
// As we know these bytes are valid, we can use `unwrap()`
let outstr = str::from_utf8_mut(&mut hellorust).unwrap();
assert_eq!("Hello, Rust!", outstr);Incorrect bytes:
// Some invalid bytes in a mutable vector
let mut invalid = vec![128, 223];
assert!(str::from_utf8_mut(&mut invalid).is_err());See the docs for Utf8Error for more details on the kinds of
errors that can be returned.
1.87.0 (const: 1.87.0) · Sourcepub const unsafe fn from_utf8_unchecked(v: &[u8]) -> &str
pub const unsafe fn from_utf8_unchecked(v: &[u8]) -> &str
1.87.0 (const: 1.87.0) · Sourcepub const unsafe fn from_utf8_unchecked_mut(v: &mut [u8]) -> &mut str
pub const unsafe fn from_utf8_unchecked_mut(v: &mut [u8]) -> &mut str
Converts a slice of bytes to a string slice without checking that the string contains valid UTF-8; mutable version.
See the immutable version, from_utf8_unchecked() for documentation and safety requirements.
§Examples
Basic usage:
1.9.0 (const: 1.86.0) · Sourcepub const fn is_char_boundary(&self, index: usize) -> bool
pub const fn is_char_boundary(&self, index: usize) -> bool
Checks that index-th byte is the first byte in a UTF-8 code point
sequence or the end of the string.
The start and end of the string (when index == self.len()) are
considered to be boundaries.
Returns false if index is greater than self.len().
§Examples
1.91.0 (const: 1.91.0) · Sourcepub const fn floor_char_boundary(&self, index: usize) -> usize
pub const fn floor_char_boundary(&self, index: usize) -> usize
Finds the closest x not exceeding index where is_char_boundary(x) is true.
This method can help you truncate a string so that it’s still valid UTF-8, but doesn’t exceed a given number of bytes. Note that this is done purely at the character level and can still visually split graphemes, even though the underlying characters aren’t split. For example, the emoji 🧑🔬 (scientist) could be split so that the string only includes 🧑 (person) instead.
§Examples
1.20.0 (const: 1.83.0) · Sourcepub const unsafe fn as_bytes_mut(&mut self) -> &mut [u8]
pub const unsafe fn as_bytes_mut(&mut self) -> &mut [u8]
Converts a mutable string slice to a mutable byte slice.
§Safety
The caller must ensure that the content of the slice is valid UTF-8
before the borrow ends and the underlying str is used.
Use of a str whose contents are not valid UTF-8 is undefined behavior.
§Examples
Basic usage:
let mut s = String::from("Hello");
let bytes = unsafe { s.as_bytes_mut() };
assert_eq!(b"Hello", bytes);Mutability:
1.0.0 (const: 1.32.0) · Sourcepub const fn as_ptr(&self) -> *const u8
pub const fn as_ptr(&self) -> *const u8
Converts a string slice to a raw pointer.
As string slices are a slice of bytes, the raw pointer points to a
u8. This pointer will be pointing to the first byte of the string
slice.
The caller must ensure that the returned pointer is never written to.
If you need to mutate the contents of the string slice, use as_mut_ptr.
§Examples
1.36.0 (const: 1.83.0) · Sourcepub const fn as_mut_ptr(&mut self) -> *mut u8
pub const fn as_mut_ptr(&mut self) -> *mut u8
Converts a mutable string slice to a raw pointer.
As string slices are a slice of bytes, the raw pointer points to a
u8. This pointer will be pointing to the first byte of the string
slice.
It is your responsibility to make sure that the string slice only gets modified in a way that it remains valid UTF-8.
1.0.0 · Sourcepub fn chars(&self) -> Chars<'_>
pub fn chars(&self) -> Chars<'_>
Returns an iterator over the chars of a string slice.
As a string slice consists of valid UTF-8, we can iterate through a
string slice by char. This method returns such an iterator.
It’s important to remember that char represents a Unicode Scalar
Value, and might not match your idea of what a ‘character’ is. Iteration
over grapheme clusters may be what you actually want. This functionality
is not provided by Rust’s standard library, check crates.io instead.
§Examples
Basic usage:
let word = "goodbye";
let count = word.chars().count();
assert_eq!(7, count);
let mut chars = word.chars();
assert_eq!(Some('g'), chars.next());
assert_eq!(Some('o'), chars.next());
assert_eq!(Some('o'), chars.next());
assert_eq!(Some('d'), chars.next());
assert_eq!(Some('b'), chars.next());
assert_eq!(Some('y'), chars.next());
assert_eq!(Some('e'), chars.next());
assert_eq!(None, chars.next());Remember, chars might not match your intuition about characters:
1.0.0 · Sourcepub fn starts_with<P: Pattern>(&self, pat: P) -> bool
pub fn starts_with<P: Pattern>(&self, pat: P) -> bool
Returns true if the given pattern matches a prefix of this
string slice.
Returns false if it does not.
The pattern can be a &str, in which case this function will return true if
the &str is a prefix of this string slice.
The pattern can also be a char, a slice of chars, or a
function or closure that determines if a character matches.
These will only be checked against the first character of this string slice.
Look at the second example below regarding behavior for slices of chars.
§Examples
1.0.0 · Sourcepub fn parse<F: FromStr>(&self) -> Result<F, F::Err>
pub fn parse<F: FromStr>(&self) -> Result<F, F::Err>
Parses this string slice into another type.
Because parse is so general, it can cause problems with type
inference. As such, parse is one of the few times you’ll see
the syntax affectionately known as the ‘turbofish’: ::<>. This
helps the inference algorithm understand specifically which type
you’re trying to parse into.
parse can parse into any type that implements the FromStr trait.
§Errors
Will return Err if it’s not possible to parse this string slice into
the desired type.
§Examples
Basic usage:
Using the ‘turbofish’ instead of annotating four:
Failing to parse:
Sourcepub const fn as_str(&self) -> &str
🔬This is a nightly-only experimental API. (str_as_str #130366)
pub const fn as_str(&self) -> &str
str_as_str #130366)Returns the same string as a string slice &str.
This method is redundant when used directly on &str, but
it helps dereferencing other string-like types to string slices,
for example references to Box<str> or Arc<str>.
Trait Implementations§
Source§impl<'b> Pattern for &'b str
Non-allocating substring search.
impl<'b> Pattern for &'b str
Non-allocating substring search.
Will handle the pattern "" as returning empty matches at each character
boundary.
§Examples
Source§fn is_prefix_of(self, haystack: &str) -> bool
🔬This is a nightly-only experimental API. (pattern #27721)
fn is_prefix_of(self, haystack: &str) -> bool
pattern #27721)Checks whether the pattern matches at the front of the haystack.
Source§type Searcher<'a> = StrSearcher<'a, 'b>
type Searcher<'a> = StrSearcher<'a, 'b>
pattern #27721)Source§fn into_searcher(self, haystack: &str) -> StrSearcher<'_, 'b>
fn into_searcher(self, haystack: &str) -> StrSearcher<'_, 'b>
pattern #27721)self and the haystack to search in.1.20.0 (const: unstable) · Source§impl SliceIndex<str> for Range<usize>
Implements substring slicing with syntax &self[begin .. end] or &mut self[begin .. end].
impl SliceIndex<str> for Range<usize>
Implements substring slicing with syntax &self[begin .. end] or &mut self[begin .. end].
Returns a slice of the given string from the byte range
[begin, end).
This operation is O(1).
Prior to 1.20.0, these indexing operations were still supported by
direct implementation of Index and IndexMut.
§Panics
Panics if begin or end does not point to the starting byte offset of
a character (as defined by is_char_boundary), if begin > end, or if
end > len.
§Examples
Source§fn get(self, slice: &str) -> Option<&Self::Output>
fn get(self, slice: &str) -> Option<&Self::Output>
slice_index_methods)Source§fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output>
fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output>
slice_index_methods)Source§unsafe fn get_unchecked(self, slice: *const str) -> *const Self::Output
unsafe fn get_unchecked(self, slice: *const str) -> *const Self::Output
slice_index_methods)Source§unsafe fn get_unchecked_mut(self, slice: *mut str) -> *mut Self::Output
unsafe fn get_unchecked_mut(self, slice: *mut str) -> *mut Self::Output
slice_index_methods)1.20.0 (const: unstable) · Source§impl SliceIndex<str> for RangeFrom<usize>
Implements substring slicing with syntax &self[begin ..] or &mut self[begin ..].
impl SliceIndex<str> for RangeFrom<usize>
Implements substring slicing with syntax &self[begin ..] or &mut self[begin ..].
Returns a slice of the given string from the byte range [begin, len).
Equivalent to &self[begin .. len] or &mut self[begin .. len].
This operation is O(1).
Prior to 1.20.0, these indexing operations were still supported by
direct implementation of Index and IndexMut.
§Panics
Panics if begin does not point to the starting byte offset of
a character (as defined by is_char_boundary), or if begin > len.
Source§fn get(self, slice: &str) -> Option<&Self::Output>
fn get(self, slice: &str) -> Option<&Self::Output>
slice_index_methods)Source§fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output>
fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output>
slice_index_methods)Source§unsafe fn get_unchecked(self, slice: *const str) -> *const Self::Output
unsafe fn get_unchecked(self, slice: *const str) -> *const Self::Output
slice_index_methods)Source§unsafe fn get_unchecked_mut(self, slice: *mut str) -> *mut Self::Output
unsafe fn get_unchecked_mut(self, slice: *mut str) -> *mut Self::Output
slice_index_methods)1.20.0 (const: unstable) · Source§impl SliceIndex<str> for RangeTo<usize>
Implements substring slicing with syntax &self[.. end] or &mut self[.. end].
impl SliceIndex<str> for RangeTo<usize>
Implements substring slicing with syntax &self[.. end] or &mut self[.. end].
Returns a slice of the given string from the byte range [0, end).
Equivalent to &self[0 .. end] or &mut self[0 .. end].
This operation is O(1).
Prior to 1.20.0, these indexing operations were still supported by
direct implementation of Index and IndexMut.
§Panics
Panics if end does not point to the starting byte offset of a
character (as defined by is_char_boundary), or if end > len.
Source§fn get(self, slice: &str) -> Option<&Self::Output>
fn get(self, slice: &str) -> Option<&Self::Output>
slice_index_methods)Source§fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output>
fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output>
slice_index_methods)Source§unsafe fn get_unchecked(self, slice: *const str) -> *const Self::Output
unsafe fn get_unchecked(self, slice: *const str) -> *const Self::Output
slice_index_methods)Source§unsafe fn get_unchecked_mut(self, slice: *mut str) -> *mut Self::Output
unsafe fn get_unchecked_mut(self, slice: *mut str) -> *mut Self::Output
slice_index_methods)