1. 4
    Some tricks and tips for using for range in GoLang go pixelstech.net
  1.  

  2. 10

    In the first example, the for _, v := range will copy v, whereas for k := range won’t, as you mentioned. In many cases it doesn’t matter, but there is a performance impact that’s probably worth pointing out.

    You can also pre-allocate the res array instead of append()ing to it:

    [~/a]% go test -bench=. -benchmem .
    goos: linux
    goarch: amd64
    BenchmarkF1-2            1429686               846 ns/op             328 B/op         15 allocs/op
    BenchmarkF2-2            1905352               628 ns/op             328 B/op          6 allocs/op
    BenchmarkF3-2           17005116                69.5 ns/op            80 B/op          1 allocs/op
    

    This isn’t something you need to overly worry about in most situations, but in some cases it does matter and given that the solutions are more or less equivalent in readability, it seems to me you might as well go for the most performant option (almost 12 times faster isn’t too shabby).

    Also, arrays ([2]int{1, 2}) are pretty rare, especially in cases like this. Using []int{1, 2} to create a slice is much more standard.

    Source of the above:

    [~/a]% tail -n+1 *.go
    ==> a.go <==
    package a
    
    func f1() {
    	arr := [10]int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
    	res := []*int{}
    	for _, v := range arr {
    		v := v
    		res = append(res, &v)
    	}
    }
    
    func f2() {
    	arr := [10]int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
    	res := []*int{}
    	for k := range arr {
    		res = append(res, &arr[k])
    	}
    }
    
    func f3() {
    	arr := [10]int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
    	res := make([]*int, 10)
    	for k := range arr {
    		res[k] = &arr[k]
    	}
    }
    
    ==> a_test.go <==
    package a
    
    import "testing"
    
    func BenchmarkF1(b *testing.B) {
    	for i := 0; i < b.N; i++ {
    		f1()
    	}
    }
    
    func BenchmarkF2(b *testing.B) {
    	for i := 0; i < b.N; i++ {
    		f2()
    	}
    }
    
    func BenchmarkF3(b *testing.B) {
    	for i := 0; i < b.N; i++ {
    		f3()
    	}
    }