42

I am a newbie in Go. I can't find any official docs showing how to merge multiple strings into a new string.

What I'm expecting:

Input: "key:", "value", ", key2:", 100

Output: "Key:value, key2:100"

I want to use + to merge strings like in Java and Swift if possible.

Darshan Rivka Whittle
  • 29,749
  • 6
  • 81
  • 103
Yi Jiang
  • 3,738
  • 5
  • 26
  • 60
  • 2
    Possible duplicate of [Golang: format a string without printing?](http://stackoverflow.com/questions/11123865/golang-format-a-string-without-printing) – icza Feb 25 '16 at 00:19

4 Answers4

73

I like to use fmt's Sprintf method for this type of thing. It works like Printf in Go or C only it returns a string. Here's an example:

output := fmt.Sprintf("%s%s%s%d", "key:", "value", ", key2:", 100)

Go docs for fmt.Sprintf

Arnav Borborah
  • 9,956
  • 4
  • 32
  • 69
evanmcdonnal
  • 38,588
  • 13
  • 84
  • 107
23

You can use strings.Join, which is almost 3x faster than fmt.Sprintf. However it can be less readable.

output := strings.Join([]string{"key:", "value", ", key2:", strconv.Itoa(100)}, "")

See https://play.golang.org/p/AqiLz3oRVq

strings.Join vs fmt.Sprintf

BenchmarkFmt-4       2000000           685 ns/op
BenchmarkJoins-4     5000000           244 ns/op

Buffer

If you need to merge a lot of strings, I'd consider using a buffer rather than those solutions mentioned above.

basgys
  • 4,025
  • 24
  • 39
  • 3
    Well, if you use strconv.Itoa then you can as well concatenate strings with + – Colin Pitrat Oct 26 '17 at 15:40
  • 1
    @ColinPitrat Due to an issue on the go compiler, strings.Join of 2 or 3 elements use +, but above that it creates a byte slice for a more efficient concatenation. If you have more than two elements to concatenate, I would strongly recommend to use strings.Join. – basgys Oct 29 '17 at 21:41
2

You can simply do this:

import (
    "fmt" 
    "strconv"
)

func main() {


     result:="str1"+"str2"+strconv.Itoa(123)+"str3"+strconv.Itoa(12)
     fmt.Println(result)

}

Using fmt.Sprintf()

var s1="abc"
var s2="def"
var num =100
ans:=fmt.Sprintf("%s%d%s", s1,num,s2);
fmt.Println(ans);
Sandeep Patel
  • 3,557
  • 2
  • 14
  • 29
0

Another option:

package main
import "fmt"

func main() {
   s := fmt.Sprint("key:", "value", ", key2:", 100)
   println(s)
}

https://golang.org/pkg/fmt#Sprint

Steven Penny
  • 82,115
  • 47
  • 308
  • 348