Marker Traits - ระบุคุณสมบัติ
std::marker มี traits พิเศษที่ไม่มี methods แต่บอก compiler ว่า type มีคุณสมบัติอะไร!
Marker Traits คืออะไร?
Section titled “Marker Traits คืออะไร?”Marker traits ไม่มี methods ที่ต้อง implement แต่ใช้บอก compiler ว่า type ปลอดภัยที่จะทำอะไรบางอย่าง:
| Trait | ความหมาย |
|---|---|
Send | ส่งข้าม thread ได้ |
Sync | แชร์ reference ข้าม thread ได้ |
Copy | copy ได้โดยไม่ต้อง clone |
Sized | ขนาดรู้ตอน compile |
Unpin | ย้ายได้หลังจาก pin |
1. Send - ส่งข้าม Thread ได้
Section titled “1. Send - ส่งข้าม Thread ได้”use std::thread;use std::rc::Rc;use std::sync::Arc;
fn main() { // i32 เป็น Send - ส่งข้าม thread ได้ let number = 42; let handle = thread::spawn(move || { println!("ได้รับ: {} ใน thread ใหม่", number); }); handle.join().unwrap();
// Arc<T> เป็น Send (ถ้า T เป็น Send) let data = Arc::new(vec![1, 2, 3]); let data_clone = Arc::clone(&data);
let handle2 = thread::spawn(move || { println!("Vec ใน thread: {:?}", data_clone); }); handle2.join().unwrap();
println!("Main thread ยังมี: {:?}", data);
// Rc<T> ไม่เป็น Send - ไม่สามารถส่งข้าม thread // let rc = Rc::new(42); // thread::spawn(move || { // println!("{}", rc); // Error: Rc ไม่ implement Send! // });}เข้าสู่ระบบเพื่อดูเนื้อหาเต็ม
ยืนยันตัวตนด้วยบัญชี Google เพื่อปลดล็อกบทความทั้งหมด
Login with Google