Golang variable scope

120 阅读1分钟

Every variable in golang has a scope, without noticing it there will make some errors that can not be easily found. Let the code below illustrates it clearly:

func main() {
	dt := "20220113"
	if true {
		dt, _ := strconv.Atoi("20220114")
		fmt.Printf("inside if, dt: %v\n", dt)
	}
	fmt.Printf("outside if, dt: %v\n", dt)
}

we will get the output as below:

inside if, dt: 20220114
outside if, dt: 20220113

as you can see, the variable dt inside of if shields the outside variable with same name.