Iterating and copying through a slice in Go
I got this from the go standard library source code. I've modified a bit to make it more succinct. Very useful when you want to step through a slice but can't use a buffer.
type buffer []byte
func (buf *buffer) next(n int) (b buffer) {
b = *buf
b, *buf = b[:n], b[n:]
return
}
func main() {
block := make([]byte, 10)
buf := buffer(block)
copy(buf.next(5), "aaa")
copy(buf.next(5), "bbb")
fmt.Println(block) // [97 97 97 0 0 98 98 98 0 0]
}
Written by Oscar Del Ben
Related protips
2 Responses
Nice. Could you link up the source file from where you got it?
over 1 year ago
·
http://golang.org/src/pkg/archive/tar/common.go toward the end of the file.
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Go
Authors
Related Tags
#go
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#