字符串插值

String interpolation

在 scala 中,您可以轻松地将变量的内容包含在字符串中,如下所示:

val nm = "Arrr"
println(s"my name is , $nm")

这在 nim 中可行吗?在那种情况下,如何实现?

strfmt module features some experimental string interpolation:

import strfmt
let nm = "Arrr"
echo interp"my name is $nm"

添加您自己的 string interpolation is not particularly had,因为标准库已经提供了大部分必要的部分:

import macros, parseutils, sequtils

macro i(text: string{lit}): expr =
  var nodes: seq[PNimrodNode] = @[]
  # Parse string literal into "stuff".
  for k, v in text.strVal.interpolatedFragments:
    if k == ikStr or k == ikDollar:
      nodes.add(newLit(v))
    else:
      nodes.add(parseExpr("$(" & v & ")"))
  # Fold individual nodes into a statement list.
  result = newNimNode(nnkStmtList).add(
    foldr(nodes, a.infix("&", b)))

const
  multiplier = 3
  message = i"$multiplier times 2.5 is ${multiplier * 2.5}"

echo message
# --> 3 times 2.5 is 7.5

proc blurb(a: int): string =
  result = i"param a ($a) is not a constant"

when isMainModule:
  for f in 1..10:
    echo f.blurb

strformat module 现在被认为是实现此目的的首选方法:

import strformat
let nm = "Arrr"
echo fmt"my name is , {nm}"