Skip to content

Instantly share code, notes, and snippets.

@itczl22
Last active September 20, 2019 10:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save itczl22/b02f32ca645eec0bf4728fa76c1afb2a to your computer and use it in GitHub Desktop.
Save itczl22/b02f32ca645eec0bf4728fa76c1afb2a to your computer and use it in GitHub Desktop.
range变量
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