{"id":1248,"hash":"df3b8db4982f0c91b553bcb7e464960c1640c3a38dea014f3b4156d28281631c","pattern":"Why does gorm db.First() panic with &quot;invalid memory address or nil pointer dereference&quot;?","full_message":"I can't figure out if I've done something silly or if I've found a bug in gorm. While I'm very well aware of what \"invalid memory address or nil pointer dereference\" means, I am completely mystified as to why it appears here.\n\nIn short, I call db.First() and I receive a panic for no obvious reason.\n\nThe relevant bits of my code:\n\npackage main\n\nimport (\n    \"fmt\"\n    \"github.com/gorilla/mux\"\n    \"github.com/jinzhu/gorm\"\n    \"net/http\"\n    \"os\"\n)\n\ntype message struct {\n    gorm.Model\n    Title string\n    Body  string `sql:\"size:0\"` // blob\n}\n\nvar db = gorm.DB{} // garbage\n\nfunc messageHandler(w http.ResponseWriter, r *http.Request) {\n    vars := mux.Vars(r)\n    m := message{}\n    query := db.First(&m, vars[\"id\"])\n    if query.Error != nil {\n        if query.Error == gorm.RecordNotFound {\n            notFoundHandler(w, r)\n            return\n        } else {\n            fmt.Fprintf(os.Stderr, \"database query failed: %v\", query.Error)\n            internalServerErrorHandler(w, r)\n            return\n        }\n    }\n\n    // actually do something useful\n}\n\nfunc main() {\n    db, err := gorm.Open(\"sqlite3\", \"/tmp/gorm.db\")\n    // ...\n}\n\ndb is opened in main() in the package, and is stored as a package variable. This doesn't seem very clean, but it appears to work...\n\nThe panic:\n\n2015/07/16 20:56:12 http: panic serving [::1]:37326: runtime error: invalid memory address or nil pointer dereference\ngoroutine 26 [running]:\nnet/http.func·011()\n        /usr/lib/golang/src/net/http/server.go:1130 +0xbb\ngithub.com/jinzhu/gorm.(*DB).First(0xd28720, 0x79f220, 0xc2080b2600, 0xc2080ef220, 0x1, 0x1, 0xd)\n        /home/error/go/src/github.com/jinzhu/gorm/main.go:200 +0x154\nmain.messageHandler(0x7f4f2e785bd8, 0xc208051c20, 0xc208035790)\n        /home/error/go/src/myproject/messages.go:28 +0x2c1\nnet/http.HandlerFunc.ServeHTTP(0x9c3948, 0x7f4f2e785bd8, 0xc208051c20, 0xc208035790)\n        /usr/lib/golang/src/net/http/server.go:1265 +0x41\ngithub.com/gorilla/mux.(*Router).ServeHTTP(0xc2080d9630, 0x7f4f2e785bd8, 0xc208051c20, 0xc208035790)\n        /home/error/go/src/github.com/gorilla/mux/mux.go:98 +0x297\nnet/http.serverHandler.ServeHTTP(0xc2080890e0, 0x7f4f2e785bd8, 0xc208051c20, 0xc208035790)\n        /usr/lib/golang/src/net/http/server.go:1703 +0x19a\nnet/http.(*conn).serve(0xc208051b80)\n        /usr/lib/golang/src/net/http/server.go:1204 +0xb57\ncreated by net/http.(*Server).Serve\n        /usr/lib/golang/src/net/http/server.go:1751 +0x35e\n\n...where line 28 of my code is query := db.First(&m, vars[\"id\"])\n\nI reviewed the noted line in gorm and the First() function, but this also isn't terribly obvious.\n\n    return newScope.Set(\"gorm:order_by_primary_key\", \"ASC\").\n        inlineCondition(where...).callCallbacks(s.parent.callback.queries).db\n\nIn order to figure out what might be going on, I made the following changes to my code:\n\nFirst attempt: Is it complaining about being passed a string? Let's give it an integer instead. After all, the example uses an integer.\n\n    id, _ := strconv.Atoi(vars[\"id\"])\n    query := db.First(&m, id)\n\nPanic again, at exactly the same place.\n\nSecond attempt: Did I create my variable m the wrong way? Maybe it really needs to be allocated with new first.\n\n    m := new(message)\n    query := db.First(m, vars[\"id\"])\n\nPanic again, at exactly the same place.\n\nThird attempt: I simply hardcoded the ID to be looked up, just in case gorilla/mux was misbehaving.\n\n    m := message{}\n    query := db.First(&m, 3)\n\nPanic again, at exactly the same place.\n\nFinally, I tested with an empty database table, with a populated table requesting an ID that exists, and with a populated table requesting an ID that does not exist. In all three cases I receive the same panic.\n\nThe most interesting part of all is that apparently net/http is recovering the panic, and then my notFoundHandler() runs and I see its template output in the browser.\n\nI am currently using the mattn/go-sqlite3 driver.\n\nMy environment is Fedora 22 x86_64 with cgo 1.4.2 as provided in Fedora RPM packages.\n\n$ go version\ngo version go1.4.2 linux/amd64\n\n$ go env\nGOARCH=\"amd64\"\nGOBIN=\"\"\nGOCHAR=\"6\"\nGOEXE=\"\"\nGOHOSTARCH=\"amd64\"\nGOHOSTOS=\"linux\"\nGOOS=\"linux\"\nGOPATH=\"/home/error/go\"\nGORACE=\"\"\nGOROOT=\"/usr/lib/golang\"\nGOTOOLDIR=\"/usr/lib/golang/pkg/tool/linux_amd64\"\nCC=\"gcc\"\nGOGCCFLAGS=\"-fPIC -m64 -pthread -fmessage-length=0\"\nCXX=\"g++\"\nCGO_ENABLED=\"1\"\n\nWhat's going on? Where is this panic coming from? How do I fix it?","ecosystem":"go","package_name":"null-pointer","package_version":null,"solution":"You're shadowing your global db variable:\n\nvar db = gorm.DB{} // garbage\n\nYour initialisation in main() should be changed to:\n\nvar err error\n// Note the assignment and not initialise + assign operator\ndb, err = gorm.Open(\"sqlite3\", \"/tmp/gorm.db\")\n\nOtherwise, db is nil and results in the panic.","confidence":0.95,"source":"stackoverflow","source_url":"https://stackoverflow.com/questions/31467498/why-does-gorm-db-first-panic-with-invalid-memory-address-or-nil-pointer-deref","votes":16,"created_at":"2026-04-19T04:52:42.960086+00:00","updated_at":"2026-04-19T04:52:42.960086+00:00"}