Golang byte buffers tricks
2016-11-15 12:49
681 查看
Tricks with []byte
buffers
The following tricks are used by fasthttp. Use them in your code too.
- Standard Go functions accept nil buffers
var ( // both buffers are uninitialized dst []byte src []byte ) dst = append(dst, src...) // is legal if dst is nil and/or src is nil copy(dst, src) // is legal if dst is nil and/or src is nil (string(src) == "") // is true if src is nil (len(src) == 0) // is true if src is nil src = src[:0] // works like a charm with nil src // this for loop doesn't panic if src is nil for i, ch := range src { doSomething(i, ch) }
So throw away nil checks for
[]bytebuffers from you code. For example,
srcLen := 0 if src != nil { srcLen = len(src) }
becomes
srcLen := len(src)
- String may be appended to
[]byte
buffer withappend
dst = append(dst, "foobar"...)
[]byte
buffer may be extended to its' capacity.
buf := make([]byte, 100) a := buf[:10] // len(a) == 10, cap(a) == 100. b := a[:100] // is valid, since cap(a) == 100.
- All fasthttp functions accept nil
[]byte
buffer
statusCode, body, err := fasthttp.Get(nil, "http://google.com/") uintBuf := fasthttp.AppendUint(nil, 1234)
相关文章推荐
- golang和java的byte数组相互转换
- golang float32/64与[]byte互转
- Golang Concurrency Tricks
- Golang:根据ascii码表将int型 []byte 转换为 string
- golang float32/64与[]byte互转
- golang(Go语言) byte/[]byte 与 二进制形式字符串 互转
- FlatBuffers使用记录(Golang)
- golang中struct和[]byte的相互转换示例
- golang []byte和string相互转换
- GoLang之strings、buffers、bytes、binary包
- Golang的Json encode/decode以及[]byte和string的转换
- golang []byte和string相互转换
- Golang中结构体转byte数组
- golang []byte转string
- Byte Buffers and Non-Heap Memory
- golang: string与byte的区别
- Golang中的[]byte与16进制(String)之间的转换
- golang中struct和[]byte的相互转换
- Image Processing Tricks
- golang vim 编辑器