Go语言结构体函数结束后指针销毁,返回nil问题求助
Hey there! No worries at all—we’ve all been there as beginners fumbling with pointers in Go. Let’s break down why your MongoDB instance is coming back nil even though you can see the correct Session inside the function.
The Most Likely Culprit: Pointer Initialization Missteps
From what you’ve described, the issue almost certainly stems from how you’re initializing and returning your DB struct pointer. Here are the two most common mistakes beginners hit in this scenario:
1. Trying to Assign Fields to a Nil Pointer
If your creation function looks something like this, you’re setting yourself up for failure:
type DB struct { Session *mongo.Client } func NewMongoDB() *DB { // This declares a pointer that starts as nil—no memory allocated for the DB struct! var db *DB session, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("mongodb://localhost:27017")) if err != nil { panic(err) } // You might think you're setting db.Session here, but db is still nil // (This would actually panic at runtime, unless you're doing something else to work around it) db.Session = session fmt.Println(db.Session) // If this works, you probably re-assigned db somewhere else return db // Still returns nil! }
2. Returning a Value Instead of a Pointer (or Vice Versa)
Another common slip-up is initializing a DB value but forgetting to return its address, or vice versa. For example:
func NewMongoDB() *DB { var db DB // This is a value, not a pointer session, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("mongodb://localhost:27017")) if err != nil { panic(err) } db.Session = session fmt.Println(db.Session) // Shows correct value return db // Error: trying to return a value where a pointer is expected (won't compile, but if you adjusted types incorrectly...) }
The Fixes
Here are two correct ways to implement your DB instance creator:
Option 1: Initialize a Pointer Directly
type DB struct { Session *mongo.Client } func NewMongoDB() *DB { // Allocate memory for the DB struct and return a pointer to it db := &DB{} session, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("mongodb://localhost:27017")) if err != nil { panic(err) } // Now we're assigning to the struct the pointer points to db.Session = session fmt.Println(db.Session) // Correct value here return db // Returns the properly initialized pointer }
Option 2: Use a Struct Literal
This is a more concise way to do the same thing:
func NewMongoDB() *DB { session, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("mongodb://localhost:27017")) if err != nil { panic(err) } // Create the DB struct and return its address in one step return &DB{Session: session} }
Quick Check List
- Did you allocate memory for your DB pointer (using
&DB{}ornew(DB))? - Are you returning the same pointer you initialized (not a separate nil variable)?
- Double-check your return statement—make sure you’re not accidentally returning
nilinstead of your initialized pointer.
If you’re still stuck, sharing the full code of your creation function would help narrow it down even more!
内容的提问来源于stack exchange,提问作者user6519307

