50

I'm trying to add a value to a variable string in golang, without use printf because I'm using revel framework and this is for a web enviroment instead of console, this is the case:

data := 14
response := `Variable string content`

so I can't get variable data inside variable response, like this

response := `Variable string 14 content`

Any idea?

omalave
  • 775
  • 1
  • 8
  • 15

4 Answers4

92

Why not use fmt.Sprintf?

data := 14
response := fmt.Sprintf("Variable string %d content", data)
mu is too short
  • 426,620
  • 70
  • 833
  • 800
9

I believe that the accepted answer is already the best practice one. Just like to give an alternative option based on @Ari Pratomo answer:

package main

import (
    "fmt"
    "strconv"
)

func main() {
    data := 14
    response := "Variable string " + strconv.Itoa(data) + " content"
    fmt.Println(response) //Output: Variable string 14 content
}

It using strconv.Itoa() to convert an integer to string, so it can be concatenated with the rest of strings.

Demo: https://play.golang.org/p/VnJBrxKBiGm

Bayu
  • 2,340
  • 1
  • 26
  • 31
5

You can use text/template:

package main

import (
   "strings"
   "text/template"
)

func format(s string, v interface{}) string {
   t, b := new(template.Template), new(strings.Builder)
   template.Must(t.Parse(s)).Execute(b, v)
   return b.String()
}

func main() {
   data := 14
   response := format("Variable string {{.}} content", data)
   println(response)
}
Zombo
  • 1
  • 62
  • 391
  • 407
4

If you want to keep the string in variable rather than to print out, try like this:

data := 14
response := "Variable string" + data + "content"
Ari Pratomo
  • 1,195
  • 12
  • 8
  • 13
    `data` is an `Integer` and you can not insert directly on `String` on this way. Otherwise you will have the following error: `invalid operation: "Variable string" + data (mismatched types string and int)` – omotto Nov 01 '19 at 11:22