Concatenate a string and other types in Golang (Go)

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 main

import (
"fmt"
)

func main() {
fmt.Println(fmt.Sprintf("%s+%d","string", 1)) // string+1
fmt.Println(fmt.Sprintf("%s+%f","string", 1.0)) // string+1.000000
fmt.Println(fmt.Sprintf("%s+%t","string", true)) // string+true
fmt.Println(fmt.Sprintf("%s+%s","string", []byte("byte"))) // string+byte
fmt.Println(fmt.Sprintf("%s+%s","string", "string")) // 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 main

import (
"fmt"
)

func main() {
fmt.Println(fmt.Sprint("string", 1)) // string1
fmt.Println(fmt.Sprint("string", 1.0)) // string1.000000
fmt.Println(fmt.Sprint("string", true)) // stringtrue
fmt.Println(fmt.Sprint("string", []byte("byte"))) // stringbyte
fmt.Println(fmt.Sprint("string", "string")) // stringstring
}

+

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 main

import (
"fmt"
"strconv"
)

func main() {
fmt.Println("string" + "+" + strconv.Itoa(1)) // string+1
fmt.Println("string" + "+" + strconv.FormatBool(true)) // string+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 main

import (
"fmt"
"strconv"
"strings"
)

func main() {
fmt.Println(strings.Join([]string{"string", strconv.Itoa(1)}, "+")) // string+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