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

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

问题描述

我有一段代码,在使用 := 时出错,但是当我使用 = 时,它编译正确.我学到的是 := 只需要至少定义一个变量,其他的不需要定义,但考虑到这段代码是 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.

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

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