variable assignment in Golang

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

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&#39;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&#39;m assigning the return value to queryDoc in the first example, shouldn&#39;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&#39;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>



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

发表评论

匿名网友

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

确定