Newer
Older
01_hello / func / loop.go
yhornisse on 27 Sep 2021 392 bytes add sample
package main

import "fmt"

// NG Sample
func hoge() {
	for i := 0; i < 5; i++ {
		f := func() {
			fmt.Println(i)
		}
		defer f()
	}
}

// OK Sample
func fuga() {
	for i := 0; i < 5; i++ {
		i := i // important
		f := func() {
			fmt.Println(i)
		}
		defer f()
	}
}

func main() {
	hoge()
	/*
	   5
	   5
	   5
	   5
	   5
	*/
	fmt.Println()
	fuga()
	/*
	   4
	   3
	   2
	   1
	   0
	*/
}