Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add variable to string variable in golang

Tags:

go

revel

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?

like image 311
omalave Avatar asked Apr 13 '18 22:04

omalave


People also ask

How do I add a variable to a string in Golang?

Using += operator or String append: In Go strings, you are allowed to append a string using += operator. This operator adds a new or given string to the end of the specified string. Using Join() function: This function concatenates all the elements present in the slice of string into a single string.

How do you assign a value to a variable in Go?

name := initialvalue is the short hand syntax to declare a variable. The following program uses the short hand syntax to declare a variable count initialized to 10 . Go will automatically infer that count is of type int since it has been initialized with the integer value 10 .

How do I print a string variable in Go?

To print a variable's type, you can use the %T verb in the fmt. Printf() function format. It's the simplest and most recommended way of printing type of a variable. Alternatively, you can use the TypeOf() function from the reflection package reflect .

What does VAR mean in Golang?

var keyword in Golang is used to create the variables of a particular type having a proper name and initial value. Initialization is optional at the time of declaration of variables using var keyword that we will discuss later in this article.


2 Answers

Why not use fmt.Sprintf?

data := 14 response := fmt.Sprintf("Variable string %d content", data) 
like image 75
mu is too short Avatar answered Oct 11 '22 01:10

mu is too short


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

like image 40
Bayu Avatar answered Oct 11 '22 00:10

Bayu