60

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?

4 Answers 4

106

Why not use fmt.Sprintf?

data := 14
response := fmt.Sprintf("Variable string %d content", data)
Sign up to request clarification or add additional context in comments.

Comments

11

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

Comments

6

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)
}

Comments

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"

1 Comment

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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.