'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.
Solution 1:[1]
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
Solution 2:[2]
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.
Solution 3:[3]
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);
Solution 4:[4]
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)
}
Solution 5:[5]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Arnav Borborah |
Solution 2 | basgys |
Solution 3 | |
Solution 4 | |
Solution 5 |