視頻地址
頭條地址:https://www.ixigua.com/i6775861706447913485
源碼地址
github地址:見擴展鏈接。
講解內容
1、通道與所有權轉移
(1)例子:
use std::thread;
use std::sync::mpsc;
fn main() {
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
let val = String::from("hi");
tx.send(val).unwrap();
println!("val is {}", val);//錯誤,此處不能使用val,因為val的所有權已經move到通道里面去了
});
let received = rx.recv().unwrap();
println!("Got: {}", received);
}
2、發送多個值示例
use std::thread;
use std::sync::mpsc;
use std::time::Duration;
fn main() {
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
let vals = vec![
String::from("hi"),
String::from("from"),
String::from("the"),
String::from("thread"),
];
for val in vals {
tx.send(val).unwrap();
thread::sleep(Duration::from_secs(1));
}
});
for received in rx {
println!("Got: {}", received);
}
}
閱讀更多 令狐一衝a 的文章