Go中的可变阴影 [英] Variable shadowing in Go

查看:91
本文介绍了Go中的可变阴影的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码生成编译错误:已声明并未使用err".如果这里存在范围/阴影问题,那是由于我不了解的原理.有人可以解释吗?

The following code generates the compile error : "err declared and not used". If there is a scope/shadowing issue here, it's due to a principle I don't understand. Can someone explain?

package main

import (
    "fmt"
)

func main() {
    var (
        err error
        dto = make(map[string]interface{})
    )

    dto[`thing`],err = getThings();
    fmt.Println(dto[`thing`]);
}

func getThings() (string,error) {
    return `the thing`,nil
}

推荐答案

这不是因为有任何阴影.除了为变量赋值之外,您没有使用任何声明的err变量.

This is not because of any shadowing. You have not used err variable that is declared for anything but assigning a value to it .

根据常见问题解答

存在未使用的变量可能表明存在错误,而未使用 导入只会减慢编译速度.积累足够的未使用进口 在代码树中,事情会变得很慢.由于这些原因,请转到 都不允许

The presence of an unused variable may indicate a bug, while unused imports just slow down compilation. Accumulate enough unused imports in your code tree and things can get very slow. For these reasons, Go allows neither

如果您声明了一个变量,则必须使用它

If you declare a variable it has to be used

在给定的程序中声明了err并将其用于将数据分配给err的值完全不使用

In the given program err is declared and is being used to assign data to .The value of err is not used at all

您可以通过进行_赋值来避免此类错误

You may bipass this kind of error by doing a _ assignment

  var _ = err

或 使用

  if err != nil {
      fmt.Println(err.Error())
      return
  }

以下代码可以解决问题,但我建议使用err检查错误

The following code would solve it,but i would suggest use the err for checking error

package main

import (
    "fmt"
)

func main() {
    var (
        err error
        dto = make(map[string]interface{})
    )
    _ = err

    dto[`thing`], err = getThings()
    fmt.Println(dto[`thing`])
}

func getThings() (string, error) {
    return `the thing`, nil
}

PS:您必须使用在函数内部声明的变量,但是如果您有未使用的全局变量,则确定.也可以使用未使用的函数参数.

PS : You must use variables you declare inside functions, but it's OK if you have unused global variables. It's also OK to have unused function arguments.

这篇关于Go中的可变阴影的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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