https://forum.golangbridge.org/t/dereferencing-pointer/21201/4
//Manual derefenrece only need for map
func myProcess(a *map[string]string) { t := (*a)["whatever"] ... }
// GO auto deference if struct is pointer :
Yes, but don’t write it in that complicated way. In Go, we value readability and simplicity. Simply write:
func happyBirthday(p *person) {
p.age++
}
--------------------------------------------------------------------------------------------------------
receiver , receiver with pointer
https://go.dev/tour/methods/4
package main
import (
"fmt"
"math"
)
type Vertex struct {
X, Y float64
}
func (v Vertex) Abs() float64 {
return math.Sqrt(v.X*v.X + v.Y*v.Y)
}
func (v *Vertex) Scale(f float64) {
v.X = v.X * f
v.Y = v.Y * f
}
func main() {
v := Vertex{3, 4}
//result is 5
fmt.Println(v.Abs())
v.Scale(10)
//result is 50
fmt.Println(v.Abs())
}
# reciever with pointer changes the address of original value due to auto dereferncing
-------------------------------
https://medium.com/@jamal.kaksouri/a-comprehensive-guide-to-pointers-in-go-4acc58eb1f4d
var x int = 10var ptr *int = &x
fmt.Println(x) // output: 10
fmt.Println(ptr) // output: 0xc0000140a8
fmt.Println(*ptr) // output: 10
---------------------
var ptr *int = new(int)
fmt.Println(ptr) // output: 0xc0000160c0
fmt.Println(*ptr) // output: 0
*ptr = 10
fmt.Println(*ptr) // output: 10
ptr = nil
In this example,
we declare a pointer variable ptr
of type *int and use the new function to allocate memory for an integer value.
We then print the memory address stored in ptr,
which is the address of the newly allocated memory block.
We also print the value of *ptr, which is the value stored at the memory address,
which is initially set to 0.
We then assign the value 10 to the memory location pointed to
by ptr using the * operator. Finally, we set the pointer variable to nil,
which frees the memory block allocated by new.
-----------------------------------------------------------------------
error will occur when derefencing nil pointer
The error occurs if you try to dereference (*ptr
) a nil pointer:
https://stackoverflow.com/questions/59964619/difference-using-pointer-in-struct-fields
use pointer in struct to allow nil
allow pointer type *string to allow nil value
*namePtr derference the pointet
No comments:
Post a Comment