Last active
September 20, 2019 10:20
-
-
Save itczl22/b02f32ca645eec0bf4728fa76c1afb2a to your computer and use it in GitHub Desktop.
range变量
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"time" | |
) | |
func main() { | |
x := []int{1, 2, 3} | |
for _, v := range x { | |
// tmp := v | |
// go print(&tmp) | |
go print(&v) | |
} | |
time.Sleep(1 * time.Second) | |
} | |
func print(x *int) { | |
fmt.Printf("%v, %d\n", x, *x) | |
} | |
// 输出: | |
// 0x414020, 3 | |
// 0x414020, 3 | |
// 0x414020, 3 | |
// 在 Golang 语言规范当中就指出了range 子句中的变量只会定义一次,然后它会被重复使用 | |
// 我们在循环里面去给它们不停地赋值但是使用的变量是同一个, 可以用注释掉的代码来更正 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment