注:所有的Strings包方法,可参考:https://godoc.org/strings#,这边有一个小技巧,就是把鼠标移到对应的go包方法上面,然后按下快捷键 Shift + F1 即可跳转到对应的文档链接
目录
1、builder包
1、功能说明
// A Builder is used to efficiently build a string using Write methods.
// It minimizes memory copying. The zero value is ready to use.
// Do not copy a non-zero Builder.
通过代码上的注释翻译:构建器用于使用Write方法高效地构建字符串。它可以最小化内存复制。零值可以使用了。不要复制非零生成器。可以知道这边builder类是用来处理构造字符串的操作,在一些业务场景可能需要用到多次构造字符串的操作,所以这边用过提供Builder方法来实现最小化的复制。
2、参数说明
addr *Builder // of receiver, to detect copies by value
buf []byte
addr:以值检测拷贝
buf:Builder通过一个byte的数组来存储字符串,这也是它实现最小化拷贝字符串的原因所在
3、方法说明
Ⅰ.String
// String returns the accumulated string.
func (b *Builder) String() string {
return *(*string)(unsafe.Pointer(&b.buf))
}
把数组转换成字符串返回。
Ⅱ.Len
// Len returns the number of accumulated bytes; b.Len() == len(b.String()).
func (b *Builder) Len() int { return len(b.buf) }
返回byte数组长度,也就是字符串长度
Ⅲ.Cap
// Cap returns the capacity of the builder's underlying byte slice. It is the
// total space allocated for the string being built and includes any bytes
// already written.
func (b *Builder) Cap() int { return cap(b.buf) }
返回Byte数组容量
Ⅳ.Reset
// Reset resets the Builder to be empty.
func (b *Builder) Reset() {
b.addr = nil
b.buf = nil
}
重置Builder。也就是说重置之后所有的值都变成空,那么就可以重新开始操作其他与上一次不相关的操作,这边比较好的一个地方就是不需要再重新new一个Builder
Ⅴ.Grow
// Grow grows b's capacity, if necessary, to guarantee space for
// another n bytes. After Grow(n), at least n bytes can be written to b
// without another allocation. If n is negative, Grow panics.
func (b *Builder) Grow(n int) {
b.copyCheck()
if n < 0 {
panic("strings.Builder.Grow: negative count")
}
if cap(b.buf)-len(b.buf) < n {
b.grow(n)
}
}
// grow copies the buffer to a new, larger buffer so that there are at least n