Skip to content

Instantly share code, notes, and snippets.

@barisere
Created March 14, 2021 21:08
Show Gist options
  • Save barisere/408fbfb4a0f024bcafced1bf99544b27 to your computer and use it in GitHub Desktop.
Save barisere/408fbfb4a0f024bcafced1bf99544b27 to your computer and use it in GitHub Desktop.
package main_test
import (
"testing"
"testing/quick"
"unsafe"
)
func all(xs []*int, f func(x *int) bool) (result bool) {
result = true
for _, v := range xs {
result = result && f(v)
}
return result
}
func Test_references_to_loop_variable_outside_the_loop_have_same_value(t *testing.T) {
f := func(xs []int) bool {
var loopVariableAddress uintptr
var zeroOfUintptr uintptr
var copies = make([]*int, 0, len(xs))
for _, x := range xs {
if loopVariableAddress == zeroOfUintptr {
// Store the loop variable's address for later comparison.
loopVariableAddress = uintptr(unsafe.Pointer(&x))
}
// Copy the address of x into a slice.
copies = append(copies, &x)
// The append statement above is most likely a mistake.
// We probably mean
// copies = append(copies, &xs[index]);
// assuming `index` is the ignored loop index.
}
return all(copies, func(x *int) bool {
// All values in `copies` are the same pointer address.
return uintptr(unsafe.Pointer(x)) == loopVariableAddress && *x == *copies[0]
})
}
if err := quick.Check(f, nil); err != nil {
t.Fatal(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment