普通网友 2019-03-02 14:46
浏览 54
已采纳

在函数内部时变量变为nil

Why the db variable is nil in the getBooks function?

package main

import (
    ...
)

var db *sql.DB

func init() {
    gotenv.Load()
}

func main() {

    db, err := sql.Open("postgres", os.Getenv("ELEPHANTSQL_URL"))
    err = db.Ping()
    fmt.Println(db, err)

    router := mux.NewRouter()
    router.HandleFunc("/books", getBooks).Methods("GET")
    log.Fatal(http.ListenAndServe("localhost:8000", router))
}

func getBooks(w http.ResponseWriter, r *http.Request) {
    if db == nil {
        log.Print("!!!!!!!!!!")
        os.Exit(2)
    }
}
</div>
  • 写回答

1条回答 默认 最新

  • dongshan9619 2019-03-02 14:50
    关注

    With := you're declaring a new db variable inside the main() scope instead of assigning to the db variable at the package scope.

    You must either use just = or use another name than db.

    Try this:

    var err error
    db, err = sql.Open("postgres", os.Getenv("ELEPHANTSQL_URL"))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?