str and String

Owned String versus borrowed str, byte length versus UTF-8 boundaries, get versus slicing, and split_once.

主题页正文目前为英文。

str is a borrowed UTF-8 string slice, usually written as &str. String is an owned, growable buffer of UTF-8 bytes in the standard library (std::string::String). Neither is a module, and neither is a third-party crate. String dereferences to str, so most of the methods documented on str are available on String as well.

You cannot index a str with an integer. There is no s[0] that returns a character. Lengths and slice ranges are in bytes, and a range that lands inside a multi-byte code point panics if you use direct slicing.

Examples were compiled with rustc 1.90.0 using --edition=2024 and run as a plain binary. See the Rust 1.90.0 documentation for the complete API.

Rust reference overview →

API index

APISummary
String::from, String::push_str, Deref to strBuild an owned String, append borrowed text, and re-borrow it as &str. len reports bytes, not Unicode scalar values.
str::len, str::get, str::is_char_boundary, slicingMeasure a string in bytes, test UTF-8 boundaries, and prefer get when a range might be invalid. Direct slicing panics if the range is not a valid character boundary.
str::split_onceSplit a string at the first occurrence of a delimiter and borrow both sides. This is a method on str, not a separate parser crate.

Owned String and borrowed str

String::from and to_string() allocate an owned buffer. push_str appends a &str and may reallocate. A &str borrowed from a String cannot be held across a mutation of that String; the borrow checker rejects it. Ending the borrow, or dropping it, makes later mutation legal again.

String::from, String::push_str, Deref to str

String::from(s: &str) -> String
fn push_str(&mut self, string: &str)
fn as_str(&self) -> &str
fn len(&self) -> usize

Build an owned String, append borrowed text, and re-borrow it as &str. len reports bytes, not Unicode scalar values.

ParameterDescription
s / stringA UTF-8 string slice to copy or append. push_str takes &str and does not take ownership of a String unless you pass &owned.

Returns: from returns an owned String. as_str returns a borrowed &str tied to the lifetime of the String. len returns the byte count.

  • "Go语言" is 8 bytes: two ASCII bytes for Go and three bytes for each of the following two characters.
  • The inner block ends the borrow of text so that push('!') can run afterward. Keeping borrowed in the same scope would not compile.
rust
fn main() {
    let mut text = String::from("Go");
    text.push_str("语言");
    {
        let borrowed: &str = &text;
        println!("{borrowed} bytes={}", borrowed.len());
    }
    text.push('!');
    println!("{text}");
}

Expected output

Go语言 bytes=8
Go语言!

Related: String

Official documentation →

Byte length and UTF-8 boundaries

len() counts bytes. chars().count() counts Unicode scalar values. is_char_boundary(i) is true only when index i is the start of a code point or the end of the string.

s.get(range) returns None when the range is out of bounds or not on a character boundary. The slicing form &s[range] panics in those cases. This example uses a silent panic hook only so the panic can be observed without extra stderr output.

str::len, str::get, str::is_char_boundary, slicing

fn len(&self) -> usize
fn chars(&self) -> Chars<'_>
fn is_char_boundary(&self, index: usize) -> bool
fn get<I: SliceIndex<str>>(&self, i: I) -> Option<&I::Output>

Measure a string in bytes, test UTF-8 boundaries, and prefer get when a range might be invalid. Direct slicing panics if the range is not a valid character boundary.

ParameterDescription
index / iA byte index or a byte range. These are not character indexes. An integer index such as s[0] is not implemented for str and does not compile.

Returns: get returns Some(&str) for a valid character-boundary range, or None. Slicing returns &str or panics. is_char_boundary returns a bool.

Errors and panics

  • panic — &s[start..end] panics when the range is out of bounds or not on a char boundary. get does not panic for those cases; it returns None.
  • In "语言", each character is three bytes, so len is 6 and the first character occupies bytes 0..3. Byte 1 is not a boundary.
  • The first character can be taken with &s[0..3] or s.get(0..3). s.get(0..1) is None; &s[0..1] panics.
  • s.chars().nth(0) is the way to pick a character by count, not s[0].
rust
fn main() {
    std::panic::set_hook(Box::new(|_| {}));
    let s = "语言";
    println!("len={} chars={}", s.len(), s.chars().count());
    println!(
        "b0={} b1={} b2={} b3={}",
        s.is_char_boundary(0),
        s.is_char_boundary(1),
        s.is_char_boundary(2),
        s.is_char_boundary(3)
    );
    println!("get0-1={:?} get0-3={:?}", s.get(0..1), s.get(0..3));
    println!("slice0-3={}", &s[0..3]);
    let panicked = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        let _ = &s[0..1];
    }))
    .is_err();
    println!("slice0-1 panicked={panicked}");
}

Expected output

len=6 chars=2
b0=true b1=false b2=false b3=true
get0-1=None get0-3=Some("语")
slice0-3=语
slice0-1 panicked=true

Related: str::get, str::is_char_boundary

Official documentation →

Split at the first equals sign

split_once returns borrowed slices on each side of the first delimiter. Any later equals signs remain in the value. The result is Option, so a missing delimiter is None rather than a panic.

str::split_once

fn split_once<P: Pattern>(&self, delimiter: P) -> Option<(&str, &str)>

Split a string at the first occurrence of a delimiter and borrow both sides. This is a method on str, not a separate parser crate.

ParameterDescription
delimiterA pattern such as a char or a &str. Only the first match is used.

Returns: Some((before, after)) when the delimiter is present, otherwise None. Both slices borrow from the original string.

  • This example is the original Rust reference recipe; the section id is unchanged.
  • This handles simple key-value lines. Quoting, escapes, and variable expansion require a format-specific parser.
rust
fn main() {
    if let Some((key, value)) = "MODE=fast=local".split_once('=') {
        println!("{key}: {value}");
    }
}

Expected output

MODE: fast=local

Related: Original recipe on the Rust overview

Official documentation →