Hacker News new | ask | show | jobs
by zxcvhjkl 2938 days ago
Look at the tokio chat example: https://github.com/tokio-rs/tokio-core/blob/master/examples/...

  let line = io::read_until(reader, b'\n', Vec::new());
  let line = line.and_then(|(reader, vec)| {
     if vec.len() == 0 {
       Err(Error::new(ErrorKind::BrokenPipe, "broken pipe"))
     } else {
       Ok((reader, vec))
     }
  });

  // Convert the bytes we read into a string, and then send   that
  // string to all other connected clients.
  let line = line.map(|(reader, vec)| {
    (reader, String::from_utf8(vec))
  });
  ...
With monads we end up with much boilerplate that has nothing to do with the actual "business" logic.

Maybe you prefer that, but I prefer the code to describe just the business logic.

2 comments

The same code with `await` :)

    let (reader, vec) = await { io.read_until(reader, b'\n', Vec::new() }?;
    if vec.len() == 0 {
        return Err(Error::new(ErrorKind::BrokenPipe, "broken pipe"));
    }
    let string = String::from_utf8(vec)?;
That's why Haskell has do-notation, and Rust has async/await. :)