Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge multiple strings and int into a single string

Tags:

string

go

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.

like image 503
Yi Jiang Avatar asked Feb 25 '16 00:02

Yi Jiang


People also ask

How do you combine strings and integers?

To concatenate a string to an int value, use the concatenation operator. Here is our int. int val = 3; Now, to concatenate a string, you need to declare a string and use the + operator.

How do I put multiple strings in one string?

Concatenation is the process of appending one string to the end of another string. You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs. For string variables, concatenation occurs only at run time.

How do you combine variables and strings?

In JavaScript, we can assign strings to a variable and use concatenation to combine the variable to another string. To concatenate a string, you add a plus sign+ between the strings or string variables you want to connect. let myPet = 'seahorse'; console.


2 Answers

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

like image 167
evanmcdonnal Avatar answered Oct 10 '22 00:10

evanmcdonnal


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.

like image 26
basgys Avatar answered Oct 09 '22 23:10

basgys