The Nim language is a great statically typed modern programming language. Its built-in VM is quite powerful and can be used for compile-time calculations in order to make the program as fast as possible. Not only is it efficient, but also expressive. We shall see the juicy fruits of the elegant syntax macros in this blog. The std/strformat
is implemented by syntax macros. In a word, the core Nim is small but with macros, its possibilities are infinite.
You might have heard the f-string in Python language, which is quite neat and handy. std/strformat
implements String interpolation/format elegantly, likewise.
import std/strformat
let msg = "hello"
assert fmt"{msg}\n" == "hello\\n"
No need for extra string concatenation or obscure interpolation operations. What you see is what you get. You just need to put variables between curly bracelets. Can't it be simpler?
There was a problem before that std/strformat
cannot format floats. It was a bit depressing since std/strformat
is such an elegant and handy library, how could it be so cruel as not to work at the compile time. Worry not, the devel
compiler has supported calling it at any time by means of registering formatBiggestFloat
in VM.
import strformat
const compileTimeVarible = &"{1.236:<.2}"
echo compileTimeVarible
Now it prints the expected result: 1.2
. See, it is not difficult to contribute to an open source project. Every contribution, big or small, counts.
Top comments (0)