How do I to write a generic Go function to push bytes into a byte array?
I suppose appending to a slice is not a perfect fit, because the array should not grow. However the function should handle any array size. I am considering to slice the array just to make the function accept any array size. See my sketch below.
Is there a cleaner way?
Play: http://play.golang.org/p/Gii9-JM33E
func push(buf []byte, size int, b byte) (int, error) {
max := len(buf)
if max < 1 {
return size, fmt.Errorf("buffer underflow: max=%d char=%d", max, b)
}
if size >= max {
return size, fmt.Errorf("buffer overflow: size=%d max=%d char=%d", size, max, b)
}
buf[size] = b
return size + 1, nil
}
Usage:
buf := [3]byte{}
size := 0
var err error
size, err = push(buf[:], size, 'a')