Files
the-way-to-go_ZH_CN/eBook/16.1.md
2018-07-24 19:36:03 +08:00

41 lines
1.1 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 16.1 误用短声明导致变量覆盖
```go
var remember bool = false
if something {
remember := true //错误
}
// 使用remember
```
在此代码段中,`remember`变量永远不会在`if`语句外面变成`true`,如果`something``true`,由于使用了短声明`:=``if`语句内部的新变量`remember`将覆盖外面的`remember`变量,并且该变量的值为`true`,但是在`if`语句外面,变量`remember`的值变成了`false`,所以正确的写法应该是:
```go
if something {
remember = true
}
```
此类错误也容易在`for`循环中出现,尤其当函数返回一个具名变量时难于察觉
,例如以下的代码段:
```go
func shadow() (err error) {
x, err := check1() // x是新创建变量err是被赋值
if err != nil {
return // 正确返回err
}
if y, err := check2(x); err != nil { // y和if语句中err被创建
return // if语句中的err覆盖外面的err所以错误的返回nil
} else {
fmt.Println(y)
}
return
}
```
## 链接
- [目录](directory.md)
- 上一节:[常见的陷阱与错误](16.0.md)
- 下一节:[误用字符串](16.2.md)