Create a flushing version of print!

A flushing print macro without a newline is a very basic feature almost all languages provide out of the box, I feel like it might confuse and or discourage newcomers with its absence, furthermore it is rather odd for such a basic thing to not be part of std

I have seen the above issue and realize why print! itself does not flush stdout and so I think it might be best to implement a new macro that does maybe called printf or fprint

I am posting this here as research for an RFC as recommended by the README

1 Like

Does this need a macro? It’s stdout().lock().flush(), right?

That implies locking stdout twice, though.

So does calling print! multiple times, though, right? I thought the answer for locking, if you’re worried about it, is to lock it manually and use write! instead of print!.

don’t macros exist exactly to get rid of this sort of busywork ? it just seems unnecessarily verbose to call two functions just to print and flush the screen not to mention confusing for beginners

1 Like

For now, you can define the macro yourself:

macro_rules! print_flush {
    ( $($t:tt)* ) => {
        {
            let mut h = stdout();
            write!(h, $($t)* ).unwrap();
            h.flush().unwrap();
        }
    }
}
1 Like

What is this functionality usually named in other languages?

printf, System.out.print etc most languages flush their normal printing function and since rust does not for its own reasons I think a function should be added that does

That’s slightly incorrect. [Java System.out.print does no extra flushing.] Rather, when it thinks it’s in a try, Java flushes System.out on every write call.

I think a print-and-flush can be useful, but I disagree that it’s the default everywhere else; rather, stdout tends to be flushed “smartly” on a stdin read halt and/or a tty is detected.

Thank you I wasn’t aware of that, haven’t programmed a lot with Java either way since rust cannot smart-flush like for instance Java I would still think a new macro would be beneficial

No. Macros exist to do things like force the first argument to be a string literal, take a variadic number of parameters, etc.

Now, it might be worth it to have a function. But I’m not convinced it’s worth it to simplify stdout().lock().flush() to flush_stdout(). Edit: oh, thanks cuviper! Not needing the .lock() means things are definitely fine.

cout << "Hello world!"; doesn’t flush in C++; if you want flushing it’s cout << "Hello world!" << flush;. (And it’s not a macro.)

FWIW, you can stdout().flush() too, which will lock() internally.

1 Like

I personally disagree with that statement but I understand your argument

True but in C/C++ stdout is flushed when attempting to read from stdin which is one of the most common reason to want to write to screen without a trailing newline especially for beginners

1 Like