Simplify substituting variables in string with Golang

Viewed 3607

I'm trying to learn about the Golang language

Today I have a question about substituting variables in string with Golang

I've searched how to resolve it in golang and found 2 ways as this blog.

First way

The first way is using fmt.Sprintf, example (I've made one on Go Playground here):

msg := fmt.Sprintf("Hello %s, you have %d new messages", "Alice", 15)
fmt.Println(msg)

Second way

And the second one is using text/template package, example (I've made one on Go Playground here):

msg := "Hi {{.DisplayName}}, you have {{ .NumMessages }} new messages"

data := map[string]interface{}{
    "DisplayName": "Bob",
    "NumMessages": 15,
}

tmpl, err := template.New("msg").Parse(msg)
buf := &bytes.Buffer{}
if err = tmpl.Execute(buf, data); err != nil {
    fmt.Println(err)
}
s := buf.String()

fmt.Println(s)

I noticed that the first way is simple but it's not easy to read, and the second is very complicated (perhaps we need to create a utility function)

I've worked with JavaScript and I found that it's very simple:

displayName = "Trudy"
numMessages = 15
msg = `Hello ${displayName}, you have ${numMessages} new messages`
console.log(msg)

Is there any way we can simplify this in Golang? Because I have just learned this language so I hope to have many ideas to improve my experience.

Edit to reopen question

My hope is whether there is a similar way in Golang such as JavaScript, it is also different with the above ways with the problems I mentioned (it shouldn't use placeholder for variable as first way, not easy to read, and it is also not complicated as second)

Edit to close this question

After a while of searching, I think Golang doesn't have a simple way to avoid this problem as JavaScript. Therefore I've closed this question without any other questions.

0 Answers
Related