在go语言中,bytes.Buffer提供了高效的多个bytes连接。
举个栗子:
1)多个[]byte 连接
b1:=[]byte("this is a first string")
b2:=[]byte("this is a second string")
var buffer bytes.Buffer //Buffer是一个实现了读写方法的可变大小的字节缓冲
buffer.Write(b1)
buffer.Write(b2)
b3 :=buffer.Bytes() //得到了b1+b2的结果
2)多个string相连
str1:="this is a first string"
str2:="this is a second string"
buffer.WriteString(str1)
buffer.WriteString(str2)
str3 :=buffer.String() //得到了str1+str2的结果
同学们可能疑惑了,两个string相加不是用str1+str2么?
可以的,但是用bytes.Buffer方式更加的高效,类似于java中的stringBuffer类,
实现了字符串或者字符数组的高效连接,比+拼接方式高效了至少1个数量级。