พื้นฐาน Rust

Rust Strings: String vs &str

Rust has two string types. Learn when to use each, and how to grow, search and split text.

  • ระดับเริ่มต้น
  • อ่าน 2 นาที
  • ตัวอย่างที่รันได้ 1 ตัวอย่าง
สิ่งที่คุณจะได้เรียนรู้
  • String and &str
  • push_str and push
  • contains, split, len
Two string types
&str
  • a borrowed view
  • fixed size
  • "Hello"
String
  • owns its text
  • can grow
  • String::from("Hello")

An owned string and a borrowed view

Rust has two main string types. &str is a view of text stored somewhere else, such as a literal in your code. String owns its text and can grow.

String::from copies the literal into a String that the program owns, so push_str and push can add to it. len counts bytes, not characters. split returns the parts between the separator, one at a time.

ประเด็นสำคัญ

  1. &str borrows text stored somewhere else.
  2. String owns its text and can grow.
  3. len counts bytes, not characters.

ตัวอย่าง Rust ที่รันได้

Rust
รันโค้ด →
main.rs
fn main() {
    let greeting = "Hello"; // &str: a borrowed string slice
    let mut message = String::from(greeting); // String: owned and growable
    message.push_str(", Rust");
    message.push('!');

    println!("{message}");
    println!("length: {}", message.len());
    println!("upper: {}", message.to_uppercase());
    println!("contains Rust: {}", message.contains("Rust"));

    for word in message.split(", ") {
        println!("{word}");
    }
}
สร้างปุ่ม Run สำหรับตัวอย่างนี้ ผลลัพธ์จากการรันโค้ด
Hello, Rust!
length: 12
upper: HELLO, RUST!
contains Rust: true
Hello
Rust!

ฝึกฝน

เปิดตัวอย่างในคอมไพเลอร์ออนไลน์ ลองเปลี่ยนค่าหรือเพิ่มบรรทัด แล้วทายผลลัพธ์ก่อนกดรัน จากนั้นลองทำให้โค้ดผิดโดยตั้งใจ แล้วอ่านข้อความจากคอมไพเลอร์

เรียนบทนี้จบแล้วใช่ไหม

ทำเครื่องหมายว่าเรียนแล้วเพื่อติดตามความคืบหน้า

ถัดไป: Reverse a String →

ฝึกด้วยโจทย์

ใช้สิ่งที่เรียนในบทนี้แก้ปัญหาจริง ทุกโจทย์รันในเบราว์เซอร์ พร้อมการทดสอบทันทีและรีวิวจาก AI

โจทย์ทั้งหมด