SoFunction
Updated on 2025-03-05

Five string splicing methods in go language (summary)

+Splicing method

This method is a method I often use when writing golang. Go language uses + splicing and php. splicing. However, since the strings in golang are immutable types, using + concatenation will produce a new string that has an impact on efficiency.

func main() {
    s1 := "hello"
    s2 := "word"
    s3 := s1 + s2
    (s3) //s3 = "helloword"
}

sprintf function

s1 := "hello"
s2 := "word"
s3 := ("%s%s", s1, s2) //s3 = "helloword"

This method is also often used during development. The advantage of writing this way is that it will not directly generate temporary strings, but the efficiency seems to be not particularly high.

Join function

Using Join function we need to first introduce the strings package to call the Join function. The Join function will first calculate the length after splicing based on the content of the string array, and then apply for the corresponding size of memory and fill in the string one by one. In the case of an array already, this efficiency will be very high, and if not, it will not be very efficient. I usually use it to slice and string.

s1 := "hello"
s2 := "word"
var str []string = []string{s1, s2}
s3 := (str, "")
(s3)

function

s1 := "hello"
s2 := "word"
var bt 
(s1)
(s2)
s3 := ()
(s3)

The efficiency is much higher than the above, but I have basically never used it in development.

function

s1 := "hello"
s2 := "word"
var build 
(s1)
(s2)
s3 := ()
(s3)

The splicing method recommended by the official is similar to the above method. The official suggestion is that I am a novice and only like the first type, so generally I use + splicing. If the splicing string is longer, it is the last method. After all, saving your life is important.

ps: Use operators directly

func BenchmarkAddStringWithOperator(b *) {
    hello := "hello"
    world := "world"
    for i := 0; i < ; i++ {
        _ = hello + "," + world
    }
}

The strings in golang are immutable. Each operation will produce a new string, so many temporary and useless strings will be generated. Not only will they be useless, but they will also bring additional burdens to gc, so the performance is relatively poor.

Main conclusion

  • In the event of existing string arrays, using () can have better performance
  • In some occasions where performance requirements are high, try to use () to obtain better performance
  • In the event of low performance requirements, use operators directly, and the code is shorter and clearer, which can achieve better readability.
  • If you need to splice not only strings, but also other needs such as numbers, you can consider ()

This is the end of this article about the splicing methods (summary) of five strings in the go language. For more relevant string splicing contents in the go language, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!