pointers in golang code example
Example 1: go pointers
& address of / create pointer
* dereference pointer
Example 2: go pointers
p := Vertex{1, 2}
q := &p
r := &Vertex{1, 2}
var s *Vertex = new(Vertex)
Example 3: go pointers
func main() {
i, j := 42, 2701
p := &i
fmt.Println(*p)
*p = 21
fmt.Println(i)
p = &j
*p = *p / 37
fmt.Println(j)
}
Example 4: golang pointer
package main
import "fmt"
type Person struct {
Firstname string
Lastname string
}
func pointerParameter(fullname *string) {
*fullname = "john doe"
fmt.Println("passing data with pointer", *fullname)
}
func pointerStructParameter(person *Person) {
fmt.Println(*person)
}
func pointerStructParameterWithRetruning(person *Person) (pointer interface{}) {
pointer = *person
return pointer
}
func main() {
var fullname string
realNumber := 5
pointerNumber := &realNumber
number := pointerNumber
person := &Person{
Firstname: "john doe",
Lastname: "margareth",
}
var yearsPointer *int
years := &yearsPointer
pointerParameter(&fullname)
pointerStructParameter(person)
fmt.Println("real number", realNumber)
fmt.Println("pointer number", pointerNumber)
fmt.Printf("real number from pointer %v\n", *number)
fmt.Println("nil pointer", *years)
fmt.Println("read pointer paramter with returning", pointerStructParameterWithRetruning(person))
}