How to add variable to string variable in golang
Asked Answered
D

4

58

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?

Dither answered 13/4, 2018 at 22:40 Comment(0)
S
103

Why not use fmt.Sprintf?

data := 14
response := fmt.Sprintf("Variable string %d content", data)
Stupid answered 13/4, 2018 at 22:56 Comment(0)
F
10

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

Frost answered 22/4, 2020 at 4:22 Comment(0)
G
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)
}
Groundage answered 10/4, 2021 at 19:59 Comment(0)
A
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"
Arabist answered 27/7, 2019 at 18:32 Comment(1)
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)Stralsund

© 2022 - 2024 — McMap. All rights reserved.