There are 5 ways to splice strings
Method 1: Use "+"
A string can only be accessed and cannot be modified.
Therefore, when splicing strings, memory copy is required, which will bring performance consumption.
However, it is highly readable and suitable for splicing of small strings
package main import "fmt" func main() { var ( a string = "one" b string = "two" c string = "three" stringJoin string ) stringJoin = a + b + c ("The result of using '+' to splice the string is:", stringJoin) }
Method 2: Use ()
Slice stitching suitable for string type
package main import ( "fmt" "strings" ) func main() { str := []string{"a", "b", "c"} var strJoin string = (str, ",") ("The result of using a splice string is:", strJoin) }
Method 3: Use
Other types can be spliced, but it will involve type conversion. The underlying implementation is [] byte byte facet
package main import "fmt" func main() { var ( name string = "Zhang San" age int32 = 18 str string ) str = ("Name: %s, Age: %d", name, age) str1 := (name, age) str2 := (name, age) (str) (str1) (str2) // result: // Name: Zhang San, Age: 18 // Zhang San18 // Zhang San 18 // }
Method 4: Use
Support strings, characters, unicode, but it involves conversion between strings and [] byte. The underlying [] byte has average performance because the buffer used by the WtiteString method is too long, which will cause panic. A small amount of splicing can be used.
package main import ( "bytes" "fmt" ) func main() { var ( info str string ) ("my") ("name") ("is") ("Tom") str = () ("Using splicing results are:", str) //result: //The result of using splicing is: mynameisTom}
Method 5: Use
Support strings, characters, unicode, and use unsafe.
Pointer optimizes the conversion between strings and [] bytes, and it is recommended to use them in scenarios where strings are spliced in large numbers.
var ( info str string ) ("my") ("name") ("is") ("Tom") str = () ("Using splicing results are:", str) //Using splicing results: mynameisTom
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.