Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

variable assignment in Golang

Tags:

go

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?

like image 780
FuriousGeorge Avatar asked Apr 02 '26 00:04

FuriousGeorge


1 Answers

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.

like image 193
Ainar-G Avatar answered Apr 03 '26 17:04

Ainar-G



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!