Frage

I try to populate the exported fields of a struct with content fetched from a MongoDb-database using the labix.org/v2/mgo package.

mgo uses the labix.org/v2/mgo/bson package to unmarshal the data. But the unmarshaller sets all unexported fields to their zero value.

Is there any way to prevent this behavior?

Working example:

package main

import (
    "fmt"
    "labix.org/v2/mgo/bson"
)

type Sub struct{ Int int }

type Player struct {
    Name       string
    unexpInt   int
    unexpPoint *Sub
}

func main() {
    dta,err := bson.Marshal(bson.M{"name": "ANisus"})
    if err != nil {
        panic(err)
    }

    p := &Player{unexpInt: 12, unexpPoint: &Sub{42}}

    fmt.Printf("Before: %+v\n", p)
    err = bson.Unmarshal(dta, p)
    if err != nil {
        panic(err)
    }
    fmt.Printf("After: %+v\n", p)
}

Output:

Before: &{Name: unexpInt:12 unexpPoint:0xf84005f500}
After: &{Name:ANisus unexpInt:0 unexpPoint:<nil>}
War es hilfreich?

Lösung

This is not possible. As you can see in the source code, struct values are explicitly being set to their zero value before filling in any fields.

There is no option to disable this behaviour. It is presumably in place to make sure the result of Unmarshal() only depends on the BSON data and not any prior state.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top