-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?

Flimzy
  • 60,850
  • 13
  • 104
  • 147
moon jun
  • 33
  • 1

1 Answers1

3

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
  • 289,344
  • 42
  • 658
  • 630
  • 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