在 Golang 中,字符串拼接可以使用加号(+)或 fmt.Sprintf() 函数来实现。
使用加号:
str1 := "Hello"
str2 := "world"
result := str1 + ", " + str2 + "!"
fmt.Println(result) // 输出:Hello, world!
使用 fmt.Sprintf() 函数:
str1 := "Hello"
str2 := "world"
result := fmt.Sprintf("%s, %s!", str1, str2)
fmt.Println(result) // 输出:Hello, world!
在上面的示例中,我们定义了两个字符串变量 str1 和 str2。然后,我们通过加号或 fmt.Sprintf() 函数将它们拼接起来,并将结果存储到 result 变量中。最后,我们使用 fmt.Println() 函数输出 result 变量的值。
需要注意的是,在循环中频繁拼接字符串时,应该避免直接使用加号来进行拼接。因为每次拼接都会创建一个新的字符串对象,并且原有的对象也不会被回收,容易造成内存浪费。此时,可以使用 bytes.Buffer 或 strings.Builder 来代替字符串拼接。例如:
var buffer bytes.Buffer
for i := 0; i < 10; i++ {
buffer.WriteString("hello")
}
result := buffer.String()
fmt.Println(result) // 输出:hellohellohellohellohellohellohellohellohellohello
在上面的代码中,我们首先创建了一个空的 bytes.Buffer 对象,并在循环中向其写入字符串。最后,我们通过调用 buffer.String() 方法来获取拼接好的字符串。这种方式可以减少内存分配和回收的次数,提高程序性能。




