Skip to content

Commit 0c40c84

Browse files
committed
go shadowed variabvles
1 parent b9f7f11 commit 0c40c84

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed

go-note/tricks.rst

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,22 @@ go初学者常见错误
1212
Go tricks
1313
--------------------------------------------------
1414

15+
影子变量(Shadowed variables)
16+
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
17+
18+
.. code-block:: go
19+
20+
// https://yourbasic.org/golang/gotcha-shadowing-variables/
21+
func main() {
22+
n := 0
23+
if true {
24+
n := 1
25+
n++
26+
}
27+
fmt.Println(n) // 0,注意 if 作用与里边使用 := 赋值隐藏了外部的 n,所以原来的 n 打印还是 0
28+
// 如果想要修改 n,直接用 n = 1
29+
}
30+
1531
golang cannot refer to unexported field or method
1632
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
1733

0 commit comments

Comments
 (0)