tap icon indicating copy to clipboard operation
tap copied to clipboard

Should tap allow the closure to return an ignorable value?

Open hzqd opened this issue 3 years ago • 1 comments

I code this:

use std::io::stdin;
String::new().tap_mut(|s| stdin().read_line(s).unwrap())

Getting error message:

xx |     String::new().tap_mut(|s| stdin().read_line(s).unwrap())
   |                               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `()`, found `usize`

It can be solved by adding brace and semicolon to the closure, but that doesn't seem ergonomic enough.

Do you think tap should allow the closure to return an ignorable value?

hzqd avatar Jan 10 '22 05:01 hzqd

I don't think it should, because it introduces a new class of potential bugs. The current design prevents the user from falling into the trap of thinking that tap returns the value that the closure returns.

Here's a contrived example where the user might believe that this would print "HELLO HELLO", but it would only print "HELLO".

use tap::prelude::*;

fn echoed(s: &str) -> String {
    s.to_string() + " " + s
}

fn main() {
    let echo = "hello".to_ascii_uppercase().tap(|s| echoed(s));
    println!("{echo}");
}

tgnottingham avatar May 16 '22 21:05 tgnottingham