Concatenate a string and an int in Go
Published: May 24, 2019
Recently I needed to concatenate a string and an int in Go. Googling revealed an overwhelming number of options. I’ve gathered and organized all of them in this post, including full working examples for each.
NOTE: This example concatenate the integer 1 with the string "[email protected]" to form the string "[email protected]".
fmt.Sprintf
One option is to use fmt.Sprintf
. Implementation looks like this:
package main
import (
"fmt"
)
func main() {
num := 1
email := "[email protected]"
concatenated := fmt.Sprintf("%d%s", num, email)
fmt.Println(concatenated)
}
fmt.Sprint
I personally always forget the tokens to pass to fmt.Sprintf
. fmt.Sprint
makes things easier:
package main
import (
"fmt"
)
func main() {
num := 1
email := "[email protected]"
concatenated := fmt.Sprint(num, email)
fmt.Println(concatenated)
}
strconv.Itoa
You can also use strconv.Itoa
to convert an int to a string. You can then concatenate with +
. Coming from a PHP and JavaScript background I personally find this to be the most readable / understandable.
package main
import (
"fmt"
"strconv"
)
func main() {
num := 1
email := "[email protected]"
concatenated := strconv.Itoa(num) + email
fmt.Println(concatenated)
}
I’ve also seen suggestions to use strings.Join
instead of +
. I find this to be the least readable of the all the options but apparently it performs slightly better.
package main
import (
"fmt"
"strconv"
"strings"
)
func main() {
num := 1
email := "[email protected]"
concatenated := strings.Join([]string{strconv.Itoa(num), email}, "")
fmt.Println(concatenated)
}