Technology Sharing

【Rust】String type learning

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

What is String

  • There is only one String type in Rust's core language, and that is String slice.strUsually regarded as&strborrowing.
  • The String type is provided through the standard library rather than being coded directly into the core language; it is a growable, mutable, UTF-8-encoded type.
  • strandStringThey are all utf-8 encoded.

Creating a New String

  • String is actually implemented by wrapping a vector of bytes type.
  • Use the new method to create a String:let mut s = String::new()
  • Use the to_string method to create a String:
    let data = "initial contents";
    let s = data.to_string();
    let s = "initial contents".to_string();
    
    • 1
    • 2
    • 3
  • Use the String::from method to create a string.let s = String::from("initial contents").

Update String

Appending strings using push_str and push

let mut s = String::from("foo");
s.push_str("bar");
// s is foobar
  • 1
  • 2
  • 3

push_strThis method does not change the ownership of the string.

let mut s = String::from("lo");
s.push('l');
// s is lol
  • 1
  • 2
  • 3

Concatenate strings using the + operator or the format! macro

let s1 = String::from("Hello, ");
let s2 = String::from("world!");
let s3 = s1 + &s2; // note s1 has been moved here and can no longer be used
  • 1
  • 2
  • 3
let s1 = String::from("tic");
let s2 = String::from("tac");
let s3 = String::from("toe");

let s = format!("{s1}-{s2}-{s3}");
  • 1
  • 2
  • 3
  • 4
  • 5

Rust does not allow subscripting of individual characters in a string.

Methods for iterating over strings

  • You can access individual Unicode characters using the chars method and access each byte using the bytes method.
for c in "Зд".chars() {
    println!("{c}");
}
  • 1
  • 2
  • 3