英文:
variable assignment in Golang
问题
所以我有以下两个方法:
func Marshal(in interface{}) (out []byte, err error)
func readDocument(r io.Reader) ([]byte, error)
在我的代码中,我做了以下操作:
queryDoc, err := readDocument(client) // queryDoc 是长度为 408 的切片
if something {
queryDoc, err := bson.Marshal(something)
newDocLen := len(queryDoc) // len 现在是 200
}
len(queryDoc) // len 是 408???
由于某种原因,queryDoc 在解组后没有得到更新。然而,如果我将其赋值给一个中间变量,它就可以工作:
```go
queryDoc, err := readDocument(client) // queryDoc 是长度为 408 的切片
if something {
q, err := bson.Marshal(something)
queryDoc = q
newDocLen := len(queryDoc) // len 现在是 200
}
len(queryDoc) // len 是 200
由于我在第一个示例中将返回值赋给了 queryDoc,那么 queryDoc 这个变量不应该引用新的数组吗?
<details>
<summary>英文:</summary>
So I have the two following methods:
func Marshal(in interface{}) (out []byte, err error)
func readDocument(r io.Reader) ([]byte, error)
In my code I do the following:
queryDoc, err := readDocument(client) // querydoc is slice of len 408
if something {
queryDoc, err := bson.Marshal(something)
newDocLen := len(queryDoc) // len is now 200
}
len(queryDoc) // len is 408????
For some reason, queryDoc doesn't get updated with the unmarshalling. If however, I assign to an intermediate value, it works:
queryDoc, err := readDocument(client) // querydoc is slice of len 408
if something {
q, err := bson.Marshal(something)
queryDoc = q
newDocLen := len(queryDoc) // len is now 200
}
len(queryDoc) // len is 200
Since I'm assigning the return value to queryDoc in the first example, shouldn't the variable queryDoc now reference the new array?
</details>
# 答案1
**得分**: 5
在
queryDoc, err := bson.Marshal(something)
中,你实际上使用了`:=`创建了一个新的`queryDoc`,而不是`=`。编译器没有捕捉到这个错误,因为你也使用了它。将其替换为
var err error
queryDoc, err = bson.Marshal(something)
应该可以按预期工作。
<details>
<summary>英文:</summary>
In
queryDoc, err := bson.Marshal(something)
you actually created a new `queryDoc` with `:=` instead of `=`. The compiler didn't catch it because you have used it as well. Replace that with
var err error
queryDoc, err = bson.Marshal(something)
and it should work as intended.
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论