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

Marker Traits - ระบุคุณสมบัติ

std::marker มี traits พิเศษที่ไม่มี methods แต่บอก compiler ว่า type มีคุณสมบัติอะไร!

Marker traits ไม่มี methods ที่ต้อง implement แต่ใช้บอก compiler ว่า type ปลอดภัยที่จะทำอะไรบางอย่าง:

Traitความหมาย
Sendส่งข้าม thread ได้
Syncแชร์ reference ข้าม thread ได้
Copycopy ได้โดยไม่ต้อง 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 เพื่อปลดล็อกบทความทั้งหมด