美文网首页RUST编程
Rust 编程视频教程(进阶)——017_2 消息传递 2

Rust 编程视频教程(进阶)——017_2 消息传递 2

作者: 令狐壹冲 | 来源:发表于2020-02-15 10:02 被阅读0次

视频地址

头条地址:https://www.ixigua.com/i6775861706447913485
B站地址:https://www.bilibili.com/video/av81202308/

源码地址

github地址:https://github.com/anonymousGiga/learn_rust

讲解内容

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);
    }
}

相关文章

网友评论

    本文标题:Rust 编程视频教程(进阶)——017_2 消息传递 2

    本文链接:https://www.haomeiwen.com/subject/qelefhtx.html