Yi Jiang
Yi Jiang

Reputation: 4028

How to merge multiple strings and int into a single string

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.

Upvotes: 51

Views: 62317

Answers (5)

Gaurav Vetron
Gaurav Vetron

Reputation: 1

Here's a simple way to combine string and integer in Go Lang(Version: go1.18.1 Latest)

package main

import (
    "fmt"
    "io"
    "os"
)

func main() {
    const name, age = "John", 26
    s := fmt.Sprintf("%s is %d years old.\n", name, age)
    io.WriteString(os.Stdout, s) // Ignoring error for simplicity.
}

Output:

John is 26 years old.

Upvotes: -1

Sandeep Patel
Sandeep Patel

Reputation: 5148

You can simply do this:

package main

    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);

Upvotes: 3

Zombo
Zombo

Reputation: 1

You can use text/template:

package main

import (
   "text/template"
   "strings"
)

func format(s string, v interface{}) string {
   t, b := new(template.Template), new(strings.Builder)
   template.Must(t.Parse(s)).Execute(b, v)
   return b.String()
}

func main() {
   s := struct{
      Key string
      Key2 int
   }{"value", 100}
   f := format("key:{{.Key}}, key2:{{.Key2}}", s)
   println(f)
}

or fmt.Sprint:

package main
import "fmt"

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

Upvotes: -1

evanmcdonnal
evanmcdonnal

Reputation: 48096

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

Upvotes: 88

basgys
basgys

Reputation: 4400

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.

Upvotes: 26

Related Questions