/* * Pointers and passing pointers in Go * If you know C, it is very similar; but considerably cleaner * * @author gtowell * Created: Aug 23, 2021 */ package main import "fmt" func main() { a := 4 // store the value 4 aa := &a // store the address (pointer) at which the 4 is stored fmt.Printf("%d %p\n", a,aa) // show the value and pointer a=126 // change 4 to 126 fmt.Printf("%d %p\n", a,aa) // value changes, pointer does not var a3 *int // Like everthing else in Go, pointers have a "zero value" fmt.Printf("Uninitialized!! %p %t\n", a3, (a3==nil)) // This line does not work when immediately follow the pointer // declaration. Problem is that declaring pointer does not allocate space //*a3 = 55 a3 = new(int) // new returns a pointer to the specified type. The space allocated gets the appropraite "zero" value fmt.Printf("Initialized!! %p %t %d\n", a3, (a3==nil), *a3) *a3 = 55 pointerpass(a3) fmt.Printf("!! %p %d\n", a3, *a3) } // can pass a pointer into a function. // This then allows the function to chaneg the value stored at the pointer // Why do this?? func pointerpass(aa3 *int) { fmt.Printf("Initialized!! %p %d\n", aa3, *aa3) *aa3 = 42 }