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?
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.
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 .
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 .
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.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With