Skip to content

Instantly share code, notes, and snippets.

@kusa-mochi
Last active June 25, 2023 08:07
Show Gist options
  • Save kusa-mochi/ae9c85ba972a333c2bccd8ba9098697c to your computer and use it in GitHub Desktop.
Save kusa-mochi/ae9c85ba972a333c2bccd8ba9098697c to your computer and use it in GitHub Desktop.
Go言語では、スコープを抜けた変数であっても参照があれば、自動的にヒープ領域に移動され値を参照し続けられるようにしてくれる。
package main
import "fmt"
func TestRoutine(ch chan *int) {
var testVar int = 123
defer func() { ch <- &testVar }()
fmt.Printf("TestRoutine - testVar:%v\n", testVar)
}
func main() {
var ch chan *int = make(chan *int)
go TestRoutine(ch)
var res *int = <-ch
close(ch)
fmt.Printf("main - testVar:%v\n", *res)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment