Go 中字符串文字中的变量捕获?

Eon*_*nil 4 syntax go string-interpolation

在 Ruby 中,我可以直接捕获字符串文字中的变量,例如bash.

SRCDIR  =   "aaa"
DSTDIR  =   "bbb"

puts "SRCDIR = #{SRCDIR}"
puts "DSTDIR = #{DSTDIR}"
Run Code Online (Sandbox Code Playgroud)

这是一个简单而微小的功能,但非常好,让它感觉像一个 shell 脚本。如果我必须编写复杂的 shell 脚本,这会很有帮助,因为这消除了替换、串联和格式表达式的需要。

Go 有这样的东西吗?如果有的话如何使用?

Eve*_*man 5

不是没有格式化字符串;通常的方法是使用fmt.Printfor fmt.Sprintf

srcdir := "aaa"
dstdir := "bbb"

// separated out Sprintf and Println for clarity
fmt.Println(fmt.Sprintf("SRCDIR = %s", srcdir))
fmt.Println(fmt.Sprintf("DSTDIR = %s", dstdir))

// could be shortened if you're just printing them
fmt.Printf("SRCDIR = %s\n", srcdir)
fmt.Printf("DSTDIR = %s\n", dstdir)
Run Code Online (Sandbox Code Playgroud)