diff --git a/about_pointers.go b/about_pointers.go new file mode 100644 index 0000000..8289d95 --- /dev/null +++ b/about_pointers.go @@ -0,0 +1,40 @@ +package go_koans + +func testPointers() { + { + a := 3 + b := a // 'b' is a copy of 'a' (all assignments are copy-operations) + + b++ + + assert(a == __int__) // variables are independent of one another + } + + { + a := 3 + b := &a // 'b' is the address of 'a' + + *b = *b + 2 // de-referencing 'b' means acting like a mutable copy of 'a' + assert(a == __int__) // pointers seem complicated at first but are actually simple + } + + { + increment := func(i int) { + i++ + } + + a := 3 + increment(a) + assert(a == __int__) // variables are always passed by value, and so a copy is made + } + + { + realIncrement := func(i *int) { + (*i)++ + } + + b := 3 + realIncrement(&b) + assert(b == __int__) // but passing a pointer allows others to mutate the value pointed to + } +} diff --git a/setup_koans_test.go b/setup_koans_test.go index 28c6db9..7d4dc55 100644 --- a/setup_koans_test.go +++ b/setup_koans_test.go @@ -27,12 +27,12 @@ func TestKoans(t *testing.T) { //testVariadicFunctions() //testFiles() //testInterfaces() - testMaps() + //testMaps() + testPointers() // TODO: ie, gameplan //testStructs() //testAllocation() - //testPointers() //testGoroutines() //testChannels() //testPanics()