Help me to understand tokio tutorial

let done = socket.incoming().map_err(|e| println!("failed to accept socket; error = {:?}", e))
                 .for_each(move |socket| {
                    Ok(())
                 });

incoming() return a stream of socket
map_err return what?
why we can call for_each after map_err

The map_err method on a stream creates a new stream based on the one it's called on, and this new stream applies the given function to every error that comes through the stream.

Since map_err returns a new stream that just does some extra work to errors, you can still call for_each on it, just like you would be able to on any other stream.

thank you
for example: if incoming() return a stream has 3 sockets and 2 errs:(socket,socket,socket,err,err)
after map_err(),a new stream has (socket,socket,socket) created,so can call for_each on it,right?

Almost! Using map_err doesn't actually delete the errors from the stream, it just replaces them with whatever the function returns. In this case you don't return anything inside the closure, so the errors are replaced with the unit type (). This means the resulting stream would contain (socket, socket, socket, (), ()).

The for_each function returns a future, which keeps running until the stream is empty or it hits an error. This future will return the first error encountered, meaning that your example code would stop running once a single error is encountered.

1 Like