package main
import (
"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("無法開啟MongoDB!")
return
}
defer session.Close()
clt := session.DB("mydb").C("userinfo")
type row struct {
UserName,
Telephone string
}
var _row, _row2 interface{}
// _row和_row2 都是interface,也就是說它們可以指向任意型別,此時是指向row結構的指標
_row = new(row)
_row2 = new(row)
// _row3 是具體struct
_row3 := row{}
log.Printf("type of &row: %v
", reflect.TypeOf(&_row))
log.Printf("type of row: %v
", reflect.TypeOf(_row2))
log.Printf("type of &row3: %v
", reflect.TypeOf(&_row3))
it := clt.Find(nil).Limit(1).Iter()
log.Println("test unmarshal using", reflect.TypeOf(&_row))
for it.Next(&_row) {
// 此時&_row是指標,指向的型別是interface
// mongo會把row當成map對待, 所有域的資訊都會輸出來
log.Println(_row)
}
it = clt.Find(nil).Limit(1).Iter()
log.Println("test unmarshal using", reflect.TypeOf(_row2))
for it.Next(_row2) {
// 此時row2是指向row結構的指標
// 只有確定了型別後,才會當成具體型別
log.Println(_row2)
}
it = clt.Find(nil).Limit(1).Iter()
log.Println("test unmarshal using", reflect.TypeOf(&_row3))
for it.Next(&_row3) {
// 只有確定了型別後,才會當成具體型別
log.Println(_row3)
}
}
輸出結果如下:
2016/04/28 16:23:22 type of &row: *interface {}
2016/04/28 16:23:22 type of row: *main.row
2016/04/28 16:23:22 type of &row3: *main.row
2016/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.row
2016/04/28 16:23:22 &{xiaoming 2222}
2016/04/28 16:23:22 test unmarshal using *main.row
2016/04/28 16:23:22 {xiaoming 2222}