dongnan4571 2017-07-14 02:18
浏览 31
已采纳

使用:=给出未使用的错误,但是使用=不在Go中

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)
  • 写回答

3条回答 默认 最新

  • dongma1666 2017-07-14 03:35
    关注

    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条)

报告相同问题?

悬赏问题

  • ¥15 vscode的问题提问
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM