英文:
why variable is nil although I put there reference to object
问题
我无法弄清楚为什么在调用ConnectToMongo
之后,变量session
仍然为nil。如果ConnectToMongo
接受的是非引用类型,比如ConnectToMongo(session mgo.Session)
,我可以理解这种情况,但是返回函数ConnectToMongo
后,引用变量类型*mgo.Session
必须被保存。
它的输出是:
nil. Why?
更新
package main
import (
"fmt"
"gopkg.in/mgo.v2"
)
func ConnectToMongo(session **mgo.Session) {
if session == nil {
var err error
*session, err = mgo.Dial("localhost:27028")
if err != nil {
panic(err)
}
}
}
func main() {
var session *mgo.Session
ConnectToMongo(&session)
if session == nil {
fmt.Println("nil. Why?")
} else {
fmt.Println("not nil. Ok.")
}
}
相同的输出:
nil. Why?
英文:
I cannot figure out why after calling ConnectToMongo
variable session
is still nil. I would understand it if ConnectToMongo
accepts not reference type like ConnectToMongo(session mgo.Session)
but reference variable type *mgo.Session
must be saved after returning function ConnectToMongo
package main
import (
"fmt"
"gopkg.in/mgo.v2"
)
func ConnectToMongo(session *mgo.Session) {
if session == nil {
var err error
session, err = mgo.Dial("localhost:27028")
if err != nil {
panic(err)
}
}
}
func main() {
var session *mgo.Session
ConnectToMongo(session)
if session == nil {
fmt.Println("nil. Why?")
}
}
It outputs:
nil. Why?
Update
package main
import (
"fmt"
"gopkg.in/mgo.v2"
)
func ConnectToMongo(session **mgo.Session) {
if session == nil {
var err error
*session, err = mgo.Dial("localhost:27028")
if err != nil {
panic(err)
}
}
}
func main() {
var session *mgo.Session
ConnectToMongo(&session)
if session == nil {
fmt.Println("nil. Why?")
} else {
fmt.Println("not nil. Ok.")
}
}
The same output:
nil. Why?
答案1
得分: 2
你需要传递一个指向指针的指针来存储指针的值。否则,你只是将指针的值复制给ConnectToMongo
函数。
package main
import (
"fmt"
"gopkg.in/mgo.v2"
)
func ConnectToMongo(session **mgo.Session) {
if *session == nil {
var err error
*session, err = mgo.Dial("localhost:27028")
if err != nil {
panic(err)
}
}
}
func main() {
var session *mgo.Session
ConnectToMongo(&session)
if session == nil {
fmt.Println("nil. Why?")
}
}
英文:
You need to pass a pointer to pointer to store the value of the pointer. Otherwise your are copying the value of the pointer to the ConnectToMongo
function.
package main
import (
"fmt"
"gopkg.in/mgo.v2"
)
func ConnectToMongo(session **mgo.Session) {
if *session == nil {
var err error
*session, err = mgo.Dial("localhost:27028")
if err != nil {
panic(err)
}
}
}
func main() {
var session *mgo.Session
ConnectToMongo(&session)
if session == nil {
fmt.Println("nil. Why?")
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论