Concatenate a string and an int in Go

Published: May 24, 2019

Tags:

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: The examples 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)
}

Max Chadwick Hi, I'm Max!

I'm a software developer who mainly works in PHP, but also dabbles in Ruby and Go. Technical topics that interest me are monitoring, security and performance.

During the day I solve challenging technical problems at Something Digital where I mainly work with the Magento platform. I also blog about tech, work on open source and hunt for bugs.

If you'd like to get in touch with me the best way is on Twitter.