一、罕用拼接办法

字符串拼接在日常开发中是很常见的需要,目前有两种广泛做法:
一种是间接用 += 来拼接

s1 := "hi "s2 := "sheng"s3 := s1 + s2  // s3 == "hi sheng"s1 += s2       // s1 == "hi sheng"

这是最罕用也是最简略直观的办法,不过简略是有代价的,golang的字符串是不可变类型,也就是说每一次对字符串的“原地”批改都会从新生成一个string,再把数据复制进去,这样一来将会产生很可观的性能开销,稍后的性能测试中将会看到这一点。

func TestS(t *testing.T) {    s := "hello"    t.Logf("%p", &s) //0xc000092350    stringHeader := (*reflect.StringHeader)(unsafe.Pointer(&s))//&{18098388 5}    t.Log(stringHeader.Data)    s += "world"    t.Logf("%p", &s) //0xc000092350    stringHeader = (*reflect.StringHeader)(unsafe.Pointer(&s))//&{824634335664 10}    t.Log(stringHeader.Data)}

输入:

0xc000092350&{18098388 5}0xc000092350&{824634335664 10}

二、