Pass method argument to function

Yes, it’s possible. You have 2 (3) options: Spec: Method expressions The expression Foo.A yields a function equivalent to A but with an explicit receiver as its first argument; it has signature func(f Foo). var foo Foo bar := func(m func(f Foo)) { m(foo) } bar(Foo.A) bar(Foo.B) bar(Foo.C) Here the method receiver is explicit. You … Read more

Golang defer behavior

That seems coherent (see also “Defer, Panic, and Recover“) Deferred function calls are executed in Last In First Out order after the surrounding function returns. This function prints “3210”: func b() { for i := 0; i < 4; i++ { defer fmt.Print(i) } } The last call when the defer is evaluated means i=3, … Read more

Collect values in order, each containing a map

The Go blog: Go maps in action has an excellent explanation. When iterating over a map with a range loop, the iteration order is not specified and is not guaranteed to be the same from one iteration to the next. Since Go 1 the runtime randomizes map iteration order, as programmers relied on the stable … Read more

How to wait for all goroutines to finish without using time.Sleep?

You can use sync.WaitGroup. Quoting the linked example: package main import ( “net/http” “sync” ) func main() { var wg sync.WaitGroup var urls = []string{ “http://www.golang.org/”, “http://www.google.com/”, “http://www.somestupidname.com/”, } for _, url := range urls { // Increment the WaitGroup counter. wg.Add(1) // Launch a goroutine to fetch the URL. go func(url string) { // … Read more

What is a concise way to create a 2D slice in Go?

There isn’t a more concise way, what you did is the “right” way; because slices are always one-dimensional but may be composed to construct higher-dimensional objects. See this question for more details: Go: How is two dimensional array’s memory representation. One thing you can simplify on it is to use the for range construct: a … Read more

Does Go provide REPL?

No, Go does not provide a REPL(read–eval–print loop). However, as already mentioned, Go Playground (this is the new URL) is very handy. The Go Authors are also thinking about adding a feature-rich editor to it. If you want something local, consider installing hsandbox. Running it simply with hsandbox go will split your terminal screen (with … Read more