/* * Program illustrating the use of pointers in Go. * In particular, this program get the address of a struct * and uses that as an alias for the struct * @author gtowell * created: July 29, 2021 */ package main import "fmt" // A simple struct type Astruct struct { aaa int bbb string } // tostring method for the struct func (p Astruct) String() string { return fmt.Sprintf("aaa:%d bbb:<<%v>>", p.aaa, p.bbb) } func main() { item := Astruct{aaa: 5, bbb: "20"} itemcopy := item itemcopy.aaa *= 4 fmt.Printf("Item:%v\n", item) fmt.Printf("Copy:%v\n", itemcopy) // note that the item and the coy are different!! itemptr := &item // the & operator get the address of "item" itemptr.aaa *= 4 // sets the value of the aaa field in the thing pointed to by itemptr. This is exactly item!!! fmt.Printf("Item:%v\n", item) // the value of aaa in item has changed fmt.Printf("Ptr :%v %p \n", itemptr, itemptr) }