2

I'm looking for a way to do things like JavaScript ES6 string template literal in Go. For example. in javascript

let name = 'espeniel';
let test = `Hi ${name}!`
console.log(test);

result

Hi epeniel! Isn't there a way to assign variables in a sentence like this even in a Go?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
moon jun
  • 83
  • 3

2 Answers2

6

Not exactly the same, but text/template and html/template packages in the standard library come very close.

The difference is that you can't use the values of Go variables defined outside of templates simply by their names, you have to pass the values you want to use in templates. But you may pass a map or struct, and you may refer to keys or struct fields (by their names) in the template.

For example:

var params = struct {
    Name string
    Age  int
}{"espeniel", 21}

t := template.Must(template.New("").Parse(`Hi {{.Name}}, you are {{.Age}}!`))

if err := t.Execute(os.Stdout, params); err != nil {
    panic(err)
}

Which outputs (try it on the Go Playground):

Hi espeniel, you are 21!

See related: Format a Go string without printing?

icza
  • 389,944
  • 63
  • 907
  • 827
  • 1
    There's also `fmt.Sprintf`, which is more concise but the format string syntax is less friendly. – Adrian Nov 11 '20 at 13:57
0

In GO you can use the fmt.sprintf function, it behave likes C one (printf)

Syntax : func Sprintf(format string, a ...interface{}) string

See Here for the docs

Here for an example