Text of rust.docs.kernel.org › next › core › primitive.str.html as Styx crawled it on Nov 19, 2026. The page may have changed since. Only its words are kept, without pictures or layout, and only the first part of a long page.

Open the live page

str - Rust

Skip to main content str Primitive Type str 1.0.0 Expand description String slices. See also the std::str module . 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: let hello_world = "Hello, World!" ; 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: let hello_world: & 'static str = "Hello, world!" ; § 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 1.0.0 (const: 1.39.0) · Source pub const fn len (&self) -> usize Returns the length of self . This length is in bytes, not char s or graphemes.

In other words, it might not be what a human considers the length of the string. § Examples let len = "foo" .len(); assert_eq! ( 3 , len); assert_eq! ( "ƒoo" .len(), 4 ); // fancy f! assert_eq! ( "ƒoo" .chars().count(), 3 ); 1.0.0 (const: 1.39.0) · Source pub const fn is_empty (&self) -> bool Returns true if self has a length of zero bytes. § Examples let s = "" ; assert! (s.is_empty()); let s = "not empty" ; assert! (!s.is_empty()); 1.87.0 (const: 1.87.0) · Source 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”: // some bytes, in a stack-allocated array let sparkle_heart = [ 240 , 159 , 146 , 150 ]; // We know these bytes are valid, so just use `unwrap()`. let sparkle_heart: & str = str::from_utf8( & sparkle_heart).unwrap(); assert_eq! ( "💖" , sparkle_heart); 1.87.0 (const: 1.87.0) · Source 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) · Source pub const unsafe fn from_utf8_unchecked (v: &[ u8 ]) -> & str Converts a slice of bytes to a string slice without checking that the string contains valid UTF-8. See the safe version, from_utf8 , for more information. § Safety The bytes passed in must be valid UTF-8. § Examples Basic usage: // some bytes, in a vector let sparkle_heart = vec! [ 240 , 159 , 146 , 150 ]; let sparkle_heart = unsafe { str::from_utf8_unchecked( & sparkle_heart) }; assert_eq! ( "💖" , sparkle_heart); 1.87.0 (const: 1.87.0) · Source 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. § Safety See the immutable version, from_utf8_unchecked() for documentation and safety requirements. § Examples Basic usage: let mut heart = vec! [ 240 , 159 , 146 , 150 ]; let heart = unsafe { str::from_utf8_unchecked_mut( &mut heart) }; assert_eq! ( "💖" , heart); 1.9.0 (const: 1.86.0) · Source 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 let s = "Löwe 老虎 Léopard" ; assert! (s.is_char_boundary( 0 )); // start of `老` assert! (s.is_char_boundary( 6 )); assert! (s.is_char_boundary(s.len())); // second byte of `ö` assert! (!s.is_char_boundary( 2 )); // third byte of `老` assert! (!s.is_char_boundary( 8 )); 1.91.0 (const: 1.91.0) · Source 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 let s = "❤️🧡💛💚💙💜" ; assert_eq! (s.len(), 26 ); assert! (!s.is_char_boundary( 13 )); let closest = s.floor_char_boundary( 13 ); assert_eq! (closest, 10 ); assert_eq! ( & s[..closest], "❤️🧡" ); 1.91.0 (const: 1.91.0) · Source pub const fn ceil_char_boundary (&self, index: usize ) -> usize Finds the closest x not below index where is_char_boundary(x) is true .

If index is greater than the length of the string, this returns the length of the string. This method is the natural complement to floor_char_boundary . See that method for more details. § Examples let s = "❤️🧡💛💚💙💜" ; assert_eq! (s.len(), 26 ); assert! (!s.is_char_boundary( 13 )); let closest = s.ceil_char_boundary( 13

The rest of this page is on the live site.