70 lines
2.1 KiB
Go
Raw Normal View History

2019-04-24 22:32:35 +03:00
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
2019-10-30 19:34:44 +03:00
// For more tutorials : https://learngoprogramming.com
// In-person training : https://www.linkedin.com/in/inancgumus/
// Follow me on twitter: https://twitter.com/inancgumus
2019-04-24 22:32:35 +03:00
package main
import "fmt"
func main() {
var (
counter int
V int
P *int
)
counter = 100 // counter is an int variable
P = &counter // P is a pointer int variable
V = *P // V is a int variable (a copy of counter)
2019-07-01 15:30:36 +03:00
if P == nil {
fmt.Printf("P is nil and its address is %p\n", P)
}
2019-04-24 22:32:35 +03:00
if P == &counter {
2019-07-01 15:30:36 +03:00
fmt.Printf("P is equal to counter's address: %p == %p\n",
P, &counter)
2019-04-24 22:32:35 +03:00
}
2019-07-01 15:30:36 +03:00
fmt.Printf("counter: %-13d addr: %-13p\n", counter, &counter)
fmt.Printf("P : %-13p addr: %-13p *P: %-13d\n", P, &P, *P)
fmt.Printf("V : %-13d addr: %-13p\n", V, &V)
2019-04-24 22:32:35 +03:00
2019-07-01 15:30:36 +03:00
fmt.Println("\n••••• change counter")
2019-04-24 22:32:35 +03:00
counter = 10 // V doesn't change because it's a copy
2019-07-01 15:30:36 +03:00
fmt.Printf("counter: %-13d addr: %-13p\n", counter, &counter)
fmt.Printf("V : %-13d addr: %-13p\n", V, &V)
2019-04-24 22:32:35 +03:00
2019-07-01 15:30:36 +03:00
fmt.Println("\n••••• change counter in passVal()")
2019-04-24 22:32:35 +03:00
counter = passVal(counter)
2019-07-01 15:30:36 +03:00
fmt.Printf("counter: %-13d addr: %-13p\n", counter, &counter)
2019-04-24 22:32:35 +03:00
2019-07-01 15:30:36 +03:00
fmt.Println("\n••••• change counter in passPtrVal()")
2019-04-24 22:32:35 +03:00
passPtrVal(&counter) // same as passPtrVal(&counter) (no need to return)
2019-04-30 15:53:23 +03:00
passPtrVal(&counter) // same as passPtrVal(&counter) (no need to return)
2019-07-01 15:30:36 +03:00
fmt.Printf("counter: %-13d addr: %-13p\n", counter, &counter)
2019-04-24 22:32:35 +03:00
}
// *pn is a int pointer variable (copy of P)
func passPtrVal(pn *int) {
2019-07-01 15:30:36 +03:00
fmt.Printf("pn : %-13p addr: %-13p *pn: %d\n", pn, &pn, *pn)
2019-04-24 22:32:35 +03:00
// pointers can breach function isolation borders
*pn++ // counter changes because `pn` points to `counter` — (*pn)++
2019-07-01 15:30:36 +03:00
fmt.Printf("pn : %-13p addr: %-13p *pn: %d\n", pn, &pn, *pn)
2019-04-30 15:53:23 +03:00
// setting it to nil doesn't effect the caller (the main function)
pn = nil
2019-04-24 22:32:35 +03:00
}
// n is a int variable (copy of counter)
func passVal(n int) int {
n = 50 // counter doesn't change because `n` is a copy
2019-07-01 15:30:36 +03:00
fmt.Printf("n : %-13d addr: %-13p\n", n, &n)
2019-04-24 22:32:35 +03:00
return n
}