Skip to content

Instantly share code, notes, and snippets.

@yonekawa
Created October 18, 2017 07:16
Show Gist options
  • Save yonekawa/7c41bd782623b10f17a64750d78e2a84 to your computer and use it in GitHub Desktop.
Save yonekawa/7c41bd782623b10f17a64750d78e2a84 to your computer and use it in GitHub Desktop.
Defer playground
package main
import "sync"
// deferはreturnの後だよ
func A() string {
str := "A"
defer func() {
str = "B"
}()
defer func() {
str = "C"
}()
defer func() {
str = "D"
}()
return str
}
// named returnだと戻り値を上書きできるよ
func B() (str string) {
str = "A"
defer func() {
str = "B"
}()
defer func() {
str = "C"
}()
defer func() {
str = "D"
}()
return str
}
func C() {
str := "1"
print(str)
// その時の変数はキャプチャされるよ
defer func() {
print(str)
}()
str = "2"
print(str)
}
func D() {
str := "1"
print(str)
// 関数スコープで定義するとその時点の値が取れるよ
defer func(s string) {
print(s)
}(str)
str = "2"
print(str)
}
// Goroutine
func E() {
var wg sync.WaitGroup
for _, s := range []string{"A", "B", "C"} {
wg.Add(1)
go func(s string) {
defer print(s)
wg.Done()
}(s)
}
println("Start")
wg.Wait()
println()
println("End")
}
func main() {
print(A())
println()
print(B())
println()
C()
println()
D()
println()
E()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment