使用:=给出未使用的错误,但是使用=不在Go中 [英] using := gives unused error but using = don't in Go

查看:91
本文介绍了使用:=给出未使用的错误,但是使用=不在Go中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一段代码,当我使用:=时会出错,但是当我使用=时它会正确编译.我了解到:=仅需要定义至少一个变量,而不必定义其他变量,但是考虑到此代码,这是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?

无法编译的代码:

错误:services/db_service.go:16:已声明会话且未使用

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()
}

已编译的代码

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()
}

更改为

Session, err := mgo.Dial(url) 

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

推荐答案

运算符:=用于短变量声明.它声明并初始化变量.

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

在第一个示例中,您已在全局范围中声明了Session变量,并且在main函数中已声明了一个在主范围中具有相同名称的新变量(与使用:=运算符一样).因此,在全局范围中声明的Session变量未使用,因此会出错.

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.

在第二个示例中,您已使用赋值运算符=为全局变量分配了一个值,因此它不是在声明新的Session变量而是向现有的全局变量分配一个值.

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.

这篇关于使用:=给出未使用的错误,但是使用=不在Go中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆