using := gives unused error but using = don't in Go

一世执手 提交于 2020-01-03 06:01:06

问题


I have piece of code in which I get error when I use := but when I use = it compiles properly. What I learned is that := only requires only atleast one variable to be defined, others need not be defined, but considering this code is it a bug in Go?

Uncompilable code:

Error: services/db_service.go:16: Session declared and not used

package services

import (
    "gopkg.in/mgo.v2"
    "log"
)

const DB = "mmdb_dev"

var Session *mgo.Session

func InitMongo() bool {
    url := "mongodb://localhost"
    log.Println("Establishing MongoDB connection...")
    //var err error
    Session, err := mgo.Dial(url)
    if err != nil {
        log.Fatal("Cannot connect to MongoDB!")
        return true
    } else {
        return false
    }
}

func GetNewSession() mgo.Session {
    return *Session.Copy()
}

Compiled code

package services

import (
    "gopkg.in/mgo.v2"
    "log"
)

const DB = "mmdb_dev"

var Session *mgo.Session

func InitMongo() bool {
    url := "mongodb://localhost"
    log.Println("Establishing MongoDB connection...")
    var err error
    Session, err = mgo.Dial(url)
    if err != nil {
        log.Fatal("Cannot connect to MongoDB!")
        return true
    } else {
        return false
    }
}

func GetNewSession() mgo.Session {
    return *Session.Copy()
}

The change is

Session, err := mgo.Dial(url) 

to

var err error
Session, err = mgo.Dial(url)

回答1:


The operator := is used for short variable declaration. It declares and initializes the variable.

In your first example, you have declared Session variable in global scope and in main function you've declared a new variable having same name in the main scope (as you have used := operator). Therefore, the Session variable declared in the global scope is unused and hence the error.

In your second example, you have assigned global variable a value using assignment operator = and hence it is not declaring a new Session variable but assigning a value to existing global variable.

Please find an example showing difference between global and local variable.




回答2:


You are shadowing your Session variable. Your first example is creating a new Session variable and now it won't compile b/c the other is declared but unused.




回答3:


When you use := the variable definition is within the function. i.e. the scope of the variable changed, from global to local. And you're not using variable locally, hence the compilation error.



来源:https://stackoverflow.com/questions/45093599/using-gives-unused-error-but-using-dont-in-go

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!