In Ruby, I could directly capture variables in string literals like in bash
.
SRCDIR = "aaa"
DSTDIR = "bbb"
puts "SRCDIR = #{SRCDIR}"
puts "DSTDIR = #{DSTDIR}"
This is a simple and tiny feature, but very nice to make it feel like a shell script. If I have to write a complex shell script this helps a lot because this eliminates the need for substitution, concatenation and format expression.
Does Go have something like this? If it does, how to use it?
Not without a formatting string; the usual way to do this is with fmt.Printf
or 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
", srcdir)
fmt.Printf("DSTDIR = %s
", dstdir)
What Wes said. I should add that if you're using custom types, you might define a method which has the signature String() string
on them (to essentially make them satisfy the fmt.Stringer
interface) and then pass instances of these types directly to functions of the fmt
package which expect a string, such as fmt.Println()
. A simple introduction to this might be found in "Effective Go".