FuriousGeorge
FuriousGeorge

Reputation: 4699

variable assignment in Golang

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?

Upvotes: 3

Views: 1966

Answers (1)

Ainar-G
Ainar-G

Reputation: 36279

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.

Upvotes: 5

Related Questions