How to add variable to string variable in golang

Why not use fmt.Sprintf?

data := 14
response := fmt.Sprintf("Variable string %d content", data)

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


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

data := 14
response := "Variable string" + data + "content"

Tags:

Go

Revel