Last Updated: February 25, 2016
·
1.141K
· oscardelben

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]
}

2 Responses
Add your response

Nice. Could you link up the source file from where you got it?

over 1 year ago ·
over 1 year ago ·