3

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?

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for catching that! I'm a golang newbie and wasn't sure if this was some crazy nuance that was different than C. Still trying to get the hang of the := vs =. I keep wanting to use := every time I do an assignment.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.