如何处理`未使用的futures :: MapErr`警告?

时间:2019-07-07 00:42:25

标签: rust rust-tokio

请考虑以下代码段:

use std::net::SocketAddr;
use tokio::sync::mpsc::{channel, Receiver, Sender}; // 0.1.22
use tokio::{net::TcpListener, prelude::*}; // 0.1.22

fn main() {
    let addr = "127.0.0.1:8118".parse::<SocketAddr>().unwrap();
    let listener = TcpListener::bind(&addr).expect("unable to bind");
    let (sender, _): (Sender<char>, Receiver<char>) = channel(64);

    tokio::run(
        listener
            .incoming()
            .and_then(|s| tokio::io::read_to_end(s, vec![]))
            .map_err(|e| panic!("failed: {:?}", e))
            .for_each(move |(_socket, buf)| {
                let s = sender.clone();
                println!("Received: {:#?}", buf);
                let c = buf[0] as char;
                s.send(c).map_err(|e| panic!("failed: {:?}", e));
                Ok(())
            }),
    );
}

在构建时,我收到以下警告:

warning: unused `futures::future::map_err::MapErr` that must be used
  --> src/main.rs:19:17
   |
19 |                 s.send(c).map_err(|e| panic!("failed: {:?}", e));
   |                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |
   = note: #[warn(unused_must_use)] on by default
   = note: futures do nothing unless polled

我想我必须做一些与Tokio / async相关的事情,但是我不知道该怎么办。我以为tokio::run可以通过在事件循环中运行代码块来处理将来所有与之相关的问题,但看起来并非如此。在这种情况下,我需要做些特别的事情吗?

Playground link

1 个答案:

答案 0 :(得分:1)

任何“未使用”警告相同:使用值或删除它。

在这里,使用tokio::write_all将第一个字节写入套接字,并返回新的Future。这在and_then组合器中称为:

use std::net::SocketAddr;
use tokio::sync::mpsc::{channel, Receiver, Sender}; // 0.1.22
use tokio::{net::TcpListener, prelude::*}; // 0.1.22

fn main() {
    let addr = "127.0.0.1:8118".parse::<SocketAddr>().unwrap();
    let listener = TcpListener::bind(&addr).expect("unable to bind");
    let (sender, _): (Sender<char>, Receiver<char>) = channel(64);

    tokio::run({
        listener
            .incoming()
            .and_then(|s| tokio::io::read_to_end(s, vec![]))
            .map_err(|e| panic!("failed: {:?}", e))
            .inspect(|(_socket, buf)| println!("Received: {:#?}", buf))
            .and_then(move |(_socket, buf)| {
                let c = buf[0] as char;
                sender.clone().send(c).map_err(|e| panic!("failed: {:?}", e))
            })
            .for_each(|_| Ok(()))
    });
}