duanjiu6697 2014-05-30 14:24
浏览 168
已采纳

通用Go函数可将字节保存到固定大小的字节数组缓冲区中

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')
  • 写回答

2条回答 默认 最新

  • duanjiu1950 2014-05-30 14:55
    关注

    The size of an array is part if its type.

    If there's a set of sizes you know you are going to accept, you could take a buf interface{} with a type switch on the sizes you want. I would assume you know the array sizes, since they must be constant at compile time.

    Other than that you would need to use reflection to actually find the array size, and store elements within the array.

    It's very infrequent you need to use an array instead of a slice. You may want to reconsider why you have to pass arrays of varying sizes around.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制