英文:
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 < 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 < 5; i++ {
b = []int{i, i + 1, i + 2, i + 3, i + 4}
a = append(a, b)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论