This is a creation in Article, where the information may have evolved or changed.
Package Mainimport ("Gopkg.in/mgo.v2" "Log" "reflect") func main () {session, Err: = MgO. Dial ("Usr:pwd@127.0.0.1:27017/dbname") if err! = Nil {log. Fatal ("Unable to open mongodb! ") return} defer session. Close () CLT: = Session. DB ("MyDB"). C ("userinfo") type row struct {UserName, telephone string} var _row, _row2 interface{}//_ro Both W and _row2 are interface, meaning that they can point to any type, and this is a pointer to the row structure _row = new (row) _row2 = new (Row)//_ROW3 is the specific struct _ROW3: = row{} log. Printf ("Type of &row:%v\n", reflect. TypeOf (&_row)) log. Printf ("Type of row:%v\n", reflect. TypeOf (_row2)) log. Printf ("Type of &row3:%v\n", reflect. TypeOf (&_ROW3)) It: = CLT. Find (nil). Limit (1). Iter () log. Println ("Test unmarshal using", reflect. TypeOf (&_row)) for it. Next (&_row) {//&_row is a pointer at this point, the type is interface//MONGO will treat row as a map, all the domain information will be output to log. Println (_row)} it = CLT. Find (nil). Limit (1). Iter () log. Println ("Test unmarshal using", reflect. TypeOf (_ROW2)) for it. Next (_ROW2) {//This time row2 is a pointer to the row structure//only if the type is determined, it will be treated as a concrete type log. Println (_row2)} it = CLT. Find (nil). Limit (1). Iter () log. Println ("Test unmarshal using", reflect. TypeOf (&_ROW3)) for it. Next (&_ROW3) {//Only when the type is determined will it be considered as a specific type of log. Println (_ROW3)}}
The output results are as follows:
2016/04/28 16:23:22 type of &row: *interface {}2016/04/28 16:23:22 type of row: *main.row2016/04/28 16:23:22 type of &row3: *main.row2016/04/28 16:23:22 test unmarshal using *interface {}2016/04/28 16:23:22 map[_id:ObjectIdHex("5721c757a8917850b210f0ca") username:xiaoming telephone:2222 address:beijing]2016/04/28 16:23:22 test unmarshal using *main.row2016/04/28 16:23:22 &{xiaoming 2222}2016/04/28 16:23:22 test unmarshal using *main.row2016/04/28 16:23:22 {xiaoming 2222}