allocate some memory println!("the value of r: {:?}", r); // access r let color = r; // transfer ownership to `color` println!("the value of color: {:?}", color); // access color println!("the value of color: {:?}", r); // => error: use of moved value: `r` // owner `color` falls out of scope // implicit drop(owner); }
// allocate some memory println!("the value of r: {:?}", r); // access r let color: &Box<Color> = &r; // borrow a reference // access borrowed value println!("the value of color: {:?}", color); // access owned value println!("the value of color: {:?}", r); // borrower & owner are both dropped }
Color::Green, Color::Red]; // if we shallow copied... let y = x; // x frees its vector contents // y frees the *same* vector contents // double free! SEGFAULT }
= vec![Color::Red, Color::Green, Color::Red]; // the ownership of the vec *moves* to y let y = x; println!("{:?}", y); // => ok, y owns it println!("{:?}", x); // => error! use of moved value // x is already invalidated // y frees the vector contents }
Color::Green; // x is the owner of memory let y = &x; // y borrows x // everyone can read immutably borrowed memory! println!("{:?}", x); // ok! println!("{:?}", y); // ok! let k = x; // => error: cannot move out of `x` because it is borrowed }
box Color::Green; // x is the owner of memory let y = &x; // y borrows x // everyone can read immutably borrowed memory! println!("{:?}", x); // ok! println!("{:?}", y); // ok! // *copy* the reference to the Box let k = y; println!("{:?}", k); // ok! println!("{:?}", y); // ok! }
rx) = channel(); Thread::spawn(move || { tx.send("Data produced in child task").unwrap(); }).detach(); let data = rx.recv().unwrap(); println!("{:?}", data); // 1x => Data produced in child task }
(tx, rx) = channel(); for task_num in range(0u8, 8) { let tx = tx.clone(); // <-- will be captured by thread Thread::spawn(move || { let msg = format!("Task {:?} done!", task_num); tx.send(msg).unwrap(); }).detach(); } for _ in range(0u8, 8) { let data = rx.recv().unwrap(); println!("{:?}", data); } // 10x => Task N done! }