String - ข้อความ
String คือข้อความที่แก้ไขได้ เก็บเป็น UTF-8 ซึ่งรองรับทุกภาษารวมถึงภาษาไทย!
String คืออะไร?
Section titled “String คืออะไร?”Rust มี 2 ประเภทข้อความหลัก:
| Type | คำอธิบาย | ขนาด | แก้ไขได้ |
|---|---|---|---|
String | ข้อความที่เป็นเจ้าของ (owned) | ไม่จำกัด | ได้ |
&str | ข้อความที่ยืมมา (borrowed) | คงที่ | ไม่ได้ |
fn main() { // ============================================ // String vs &str // ============================================
// String - เก็บบน heap, แก้ไขได้ let mut owned = String::from("Hello"); owned.push_str(", World!"); println!("String: {}", owned);
// &str - borrowed slice, แก้ไขไม่ได้ let borrowed: &str = "Hello, World!"; // borrowed.push_str("!"); // Error! can't mutate println!("&str: {}", borrowed);
// ============================================ // ทำไมต้องมี 2 types? // ============================================
// String literals = &str (embedded ใน binary) // Text ที่สร้าง runtime = String
// &str ราคาถูกกว่า (แค่ pointer + length) // String ยืดหยุ่นกว่า (modify ได้)}เข้าสู่ระบบเพื่อดูเนื้อหาเต็ม
ยืนยันตัวตนด้วยบัญชี Google เพื่อปลดล็อกบทความทั้งหมด
Login with Google