Skip to content
เข้าสู่ระบบ

str Primitive

String slice type เป็นหนึ่งใน primitive types ที่สำคัญที่สุดใน Rust โดย str เก็บ UTF-8 encoded text และใช้เป็น borrowed slice &str เกือบทุกครั้ง เนื่องจากเป็น unsized type

หัวข้อหลัก: str Basics

Section titled “หัวข้อหลัก: str Basics”

str คือ primitive string slice type ที่แตกต่างจาก String ตรงที่ str เป็น view ไปยัง string data ที่มีอยู่แล้ว ไม่ได้ own data เอง

ความแตกต่างระหว่าง str และ String

Section titled “ความแตกต่างระหว่าง str และ String”

เข้าใจความแตกต่างนี้เป็นพื้นฐานสำคัญ: &str คือ borrowed view ส่วน String คือ owned, growable string

fn main() {
println!("=== str vs String ===\n");
println!("str (primitive):");
println!(" - Unsized type (size unknown at compile time)");
println!(" - Always used as &str (borrowed)");
println!(" - String literal type");
println!(" - Immutable view into string data");
println!();
println!("String:");
println!(" - Owned, heap-allocated");
println!(" - Growable");
println!(" - Mutable");
println!();
// String literal is &'static str
let literal: &str = "hello";
println!("Literal type: &str");
println!("Value: {}", literal);
// String to &str
let owned = String::from("world");
let slice: &str = &owned;
println!("\nString to &str: {}", slice);
// &str to String
let back_to_string: String = literal.to_string();
println!("&str to String: {}", back_to_string);
}

เข้าสู่ระบบเพื่อดูเนื้อหาเต็ม

ยืนยันตัวตนด้วยบัญชี Google เพื่อปลดล็อกบทความทั้งหมด