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

Max Chadwick Hi, I'm Max!

I'm a software developer who mainly works in PHP, but loves dabbling in other languages like Go and Ruby. Technical topics that interest me are monitoring, security and performance. I'm also a stickler for good documentation and clear technical writing.

During the day I lead a team of developers and solve challenging technical problems at Rightpoint where I mainly work with the Magento platform. I've also spoken at a number of events.

In my spare time I blog about tech, work on open source and participate in bug bounty programs.

If you'd like to get in contact, you can find me on Twitter and LinkedIn.