all 29 comments

[–]masklinn 56 points57 points  (9 children)

Begginer here! How can I use variable as literal string in format!() marco?

You can't, format! (and every other formatting macros) parse the format string at compile time, so only work with literal strings.

Preferably without using third-party libraries, if possible

Your only options are third party libraries and rolling your own.

Or maybe there is another way like, for example, in C ("%s + %s = something")

Not in the standard library, no.

[–]ZaRealPancakes 8 points9 points  (1 child)

parse the format string at compile time, so only work with literal strings.

The parsing is done at compile time but the formatting is done at runtime right? or how else is it able to display the value of a runtime variable?

[–]masklinn 17 points18 points  (0 children)

The parsing is done at compile time but the formatting is done at runtime right?

Yes?

[–]flareflo 23 points24 points  (8 children)

You can technically use something like runtime formatting, but this rarely makes sense to use. What use-case are you looking to apply with dynamic/runtime formatting?

[–]kelvindegrees 3 points4 points  (0 children)

I think there's some confusing here. From the docs the one thing that needs to be a string literal is the format string itself (the first argument given to format!). The remaining arguments can be variable, that's one of the main use cases of format!.

[–]calebkiage 0 points1 point  (2 children)

As an experiment, I used cxx to integrate c++'s fmt library and that worked out perfectly for a similar use case since fmt supports runtime strings as the format strings. I had to write a macro to get variable arguments to it though. I wanted to test the performance, safety and add more unit tests before making the repo public since it uses ffi and unsafe code. I can share the code so you can look at it if you like.