String Formatting in Nim import strformat
type
Point = object
x , y : int
proc main () =
# Nim offers excellent support for string formatting.
# Here are some examples of common string formatting tasks.
# Nim uses string interpolation with the `&` operator
# and format specifiers similar to printf traditions.
let p = Point ( x : 1 , y : 2 )
echo & "struct1: {p}"
# To include field names, we can use the `$` operator
echo & "struct2: { $p }"
# Nim doesn't have a direct equivalent to Go's %#v,
# but we can create a custom representation
echo & "struct3: Point(x: {p.x}, y: {p.y})"
# To print the type of a value, use `type()`
echo & "type: {type(p)}"
# Formatting booleans is straightforward
echo & "bool: {true}"
# There are many options for formatting integers
echo & "int: {123}"
# This prints a binary representation
echo & "bin: {14:b}"
# This prints the character corresponding to the given integer
echo & "char: {char(33)}"
# Hex encoding
echo & "hex: {456:x}"
# Formatting floats
echo & "float1: {78.9:.6f}"
# Scientific notation
echo & "float2: {1.234e8:.6e}"
echo & "float3: {1.234e8:.6E}"
# String formatting
echo & "str1: \" string \" "
# To double-quote strings, use the `escape` proc
import strutils
echo & "str2: {escape("""string""")}"
# Hex representation of a string
echo &"str3: {toHex("hex this")}"
# To print a representation of a pointer
echo &"pointer: {cast[int](addr p):x}"
# Controlling width and precision
echo &"width1: |{12:6}|{345:6}|"
echo &"width2: |{1.2:6.2f}|{3.45:6.2f}|"
echo &"width3: |{1.2:<6.2f}|{3.45:<6.2f}|"
# Formatting strings with width
echo &"width4: |{"foo":>6}|{"b":>6}|"
echo &"width5: |{"foo":<6}|{"b":<6}|"
# Nim's equivalent of Sprintf is the `&` operator
let s = &"sprintf: a {"string"}"
echo s
# To write to stderr, use the `stderr` file descriptor
stderr.writeLine &"io: an {"error"}"
main()
To run the program, save it as string_formatting.nim
and use the Nim compiler:
$ nim c -r string_formatting.nim
This will compile and run the program, producing output similar to the original Go example.
Nim’s string formatting capabilities are quite powerful, using string interpolation with the &
operator and format specifiers similar to those in other languages. The strformat
module provides this functionality.
Note that Nim doesn’t have exact equivalents for all of Go’s formatting verbs, but it offers similar capabilities through its own syntax and standard library functions.