Borrow - ยืมข้อมูล
std::borrow มี traits สำหรับจัดการการยืมข้อมูลอย่างยืดหยุ่น! เป็น module ที่ช่วยให้ API ของเรารองรับทั้ง owned และ borrowed types ได้อย่างมีประสิทธิภาพ
borrow มีอะไร?
Section titled “borrow มีอะไร?”| Type/Trait | ใช้ทำอะไร |
|---|---|
Borrow<T> | ยืมเป็น &T (สำหรับ lookups) |
BorrowMut<T> | ยืมเป็น &mut T |
ToOwned | สร้าง owned copy จาก borrowed |
Cow<T> | Clone on Write - ยืมก่อน clone เมื่อจำเป็น |
ทำไมต้องมี Borrow Trait?
Section titled “ทำไมต้องมี Borrow Trait?”use std::collections::HashMap;
fn main() { // ============================================ // Problem: HashMap<String, V> ต้องค้นหาด้วย String? // ============================================
let mut map: HashMap<String, i32> = HashMap::new(); map.insert("alice".to_string(), 100); map.insert("bob".to_string(), 200);
// ถ้าไม่มี Borrow trait ต้องทำแบบนี้: // let key = "alice".to_string(); // allocate String ใหม่! // let value = map.get(&key);
// แต่เพราะ String impl Borrow<str> เราทำแบบนี้ได้: let value = map.get("alice"); // ใช้ &str โดยตรง - ไม่ allocate! println!("alice: {:?}", value);
// ============================================ // Borrow ช่วยให้ API ยืดหยุ่นกว่า // ============================================
// ใช้ได้ทั้ง &str และ &String let key_str: &str = "bob"; let key_string: String = "alice".to_string();
println!("bob: {:?}", map.get(key_str)); println!("alice: {:?}", map.get(&key_string));}เข้าสู่ระบบเพื่อดูเนื้อหาเต็ม
ยืนยันตัวตนด้วยบัญชี Google เพื่อปลดล็อกบทความทั้งหมด
Login with Google