Closure and format!() syntax

Hi,

An interesting example:

    let sp = SpinnerBuilder::new("Long Running op!".into()).
        format(|sp, status|{
            format!("{spin} -- Currently working on: \'{status}\' -- {spin}",
                    spin = sp, status = status)
        }).start();

I can understand none of it :slight_smile: . What are names inside brackets? Rust has no string comprehension. What are format!("...", spin = sp, status = status) arguments, and what is = in this context?. I sort of guess why there are three pairs of braces, and only two arguments, yet can't actually understand it.

What is it all about?

Everything is documented in the official docs of the fmt module.

They are named placeholders which will be formatted. They correspond to the left-hand side of the assignment-looking parameters inside the format!(…) invocation.

That's just how the syntax of the format!() macro is defined. It accepts key-value pairs, so the key = value syntax is used to specify what values should be inserted wherever the corresponding placeholder occurs in the format string.

There are three uses of two arguments. You can use a single argument (named or not) more than once in a format string.

Rustc 1.58.0, due tomorrow, will stabilize format args capture by joshtriplett · Pull Request #90473 · rust-lang/rust · GitHub . So with that, the example could even be written at:

let sp = SpinnerBuilder::new("Long Running op!".into())
    .format(|spin, status| format!("{spin} -- Currently working on: \'{status}\' -- {spin}"))
    .start();

Does this mean rust has string comprehension as of tomorrow? Maybe not, it's just macro processing, but close enough for me. :sunglasses:

3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.