How it works...

The format! macro combines strings by accepting a format string filled with formatting parameters (example, {}, {0}, or {foo}) and a list of arguments, which are then inserted into the placeholders.
We are now going to show this on the example in line [16]:

format!("My favourite number is {}", 42);

Let's break down the preceding line of code:

  • "My favourite number is {}" is the format string
  • {} is the formatting parameter
  • 42 is the argument

As demonstrated, format! works not only with strings, but also with numbers. In fact, it works with all structs that implement the Display trait. This means that, by providing such an implementation by yourself, you can easily make your own data structures printable however you want.

By default, format! replaces one parameter after another. If you want to override this behavior, you can use positional parameters like {0} [21]. With the knowledge that the positions are zero-indexed, the behavior here is pretty straightforward, {0} gets replaced by the first argument, {1} gets replaced by the second, and so on.

At times, this can become a bit unwieldy when using a lot of parameters. For this purpose, you can use named arguments [26], just like in Python. Keep in mind that all of your unnamed arguments have to be placed before your named ones. For example, the following is invalid:

format!("{message} {}", message="Hello there,", "friendo")

It should be rewritten as:

format!("{message} {}", "friendo", message="Hello there,")
// Returns "hello there, friendo"
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.219.64.172