Go:将字节读入数组

huangapple go评论72阅读模式
英文:

Go: read bytes into array

问题

我正在尝试以以下方式将字节追加到数组中:

Go

func readBytes() {
    b := make([]byte, 1)
    a := [][]byte{}
    for i := 0; i < 4; i++ {
        conn.Read(b)
        a = append(a, b)
        fmt.Println(b)
    }
    fmt.Println(a)
}

fmt.Println(b) 的结果为:

[2]
[5]
[5]
[3]

fmt.Println(a) 的结果为:

[[3], [3], [3], [3]]

为什么只打印出最后一个发送的字节?我是否漏掉了什么?

英文:

I'm trying to append bytes to an array in the following way:

Go

func readBytes() {
    b := make([]byte, 1)
    a := [][]byte{}
    for i := 0, i &lt; 4, i++ {
        conn.Read(b)
        a = append(a, b)
        fmt.Println(b)
    }
    fmt.Println(a)
}

Result from fmt.Println(b):

[2]
[5]
[5]
[3]

Result from fmt.Println(a):

[[3], [3], [3], [3]]

Why does it only print out the last byte sent?? Am I missing something?

答案1

得分: 1

b是一个切片,因此每次将其传递给conn.Read时,都会更新相同的底层数组。你可以查看这篇Golang博客文章以了解其工作原理

一旦调用fmt.Println(a),每个切片都指向相同的底层数组。

你可以通过在循环中实例化缓冲区b或者使用数组而不是切片来解决这个问题。

这是一个重新分配b切片的工作示例:http://play.golang.org/p/cN1BE8WSFE

它基本上是这样的(使用int切片):

for i := 0; i < 5; i++ {
    b = []int{i, i + 1, i + 2, i + 3, i + 4}
    a = append(a, b)
}
英文:

b is a slice - and you're therefore updating the same underlying array each time you pass it to conn.Read. You can look at this Golang blog post to understand how this works.

Once you call fmt.Println(a) .. each slice is looking at the same underlying array.

You could fix this by instantiating the buffer b in the loop, or using an array instead of a slice.

Here's a working example that re-allocates the b slice inside the loop: http://play.golang.org/p/cN1BE8WSFE

It is essentially (with an int slice):

for i := 0; i &lt; 5; i++ {
	b = []int{i, i + 1, i + 2, i + 3, i + 4}
	a = append(a, b)
}

huangapple
  • 本文由 发表于 2014年11月22日 09:38:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/27073106.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定