Concatenate a string and other types
Recently I needed to concatenate a string and an int in Go. I’ve gathered and organized all of them in this post, including full working examples for each.
fmt.Sprintf
One option is to use fmt.Sprintf. Implementation looks like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 package mainimport ( "fmt" ) func main () { fmt.Println(fmt.Sprintf("%s+%d" ,"string" , 1 )) fmt.Println(fmt.Sprintf("%s+%f" ,"string" , 1.0 )) fmt.Println(fmt.Sprintf("%s+%t" ,"string" , true )) fmt.Println(fmt.Sprintf("%s+%s" ,"string" , []byte ("byte" ))) fmt.Println(fmt.Sprintf("%s+%s" ,"string" , "string" )) }
fmt.Sprintf
With tokens to pass to fmt.Sprintf makes things easier:
1 2 3 4 5 6 7 8 9 10 11 12 13 package mainimport ( "fmt" ) func main () { fmt.Println(fmt.Sprint("string" , 1 )) fmt.Println(fmt.Sprint("string" , 1.0 )) fmt.Println(fmt.Sprint("string" , true )) fmt.Println(fmt.Sprint("string" , []byte ("byte" ))) fmt.Println(fmt.Sprint("string" , "string" )) }
+
You can also use strconv.Itoa or strconv other functions to convert an int or other types to a string.
1 2 3 4 5 6 7 8 9 10 11 12 package mainimport ( "fmt" "strconv" ) func main () { fmt.Println("string" + "+" + strconv.Itoa(1 )) fmt.Println("string" + "+" + strconv.FormatBool(true )) fmt.Println("string" + "+" + strconv.FormatFloat(3.1415 , 'E' , -1 , 64 )) string +3.1415E+00 }
strings.Join
Use strings.Join instead of +.
1 2 3 4 5 6 7 8 9 10 11 package mainimport ( "fmt" "strconv" "strings" ) func main () { fmt.Println(strings.Join([]string {"string" , strconv.Itoa(1 )}, "+" )) }
References
[1] Concatenate a string and an int in Go | Max Chadwick - https://maxchadwick.xyz/blog/concatenate-a-string-and-an-int-in-go
[2] strconv - The Go Programming Language - https://golang.org/pkg/strconv
[3] Go by Example: String Formatting - https://gobyexample.com/string-formatting