Thursday, 13 February 2025

GO LANG Pointer, derefernece, nil

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 = 10
var 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

var namePtr *string // namePtr is nil fmt.Println(*namePtr) // ❌ ERROR: nil pointer dereference

Check nil

package main import "fmt" func main() { var namePtr *string // initialized pointer (nil) if namePtr == nil { fmt.Println("Pointer is nil, cannot dereference") } else { fmt.Println(*namePtr) // This won't execute// dereferencing pointer } }



// Make a pointer
namePtr := new(string)

*namePtr = "Bob" // Assign value to the dereferenced pointer



Using a Pointer for Nested Structs

type User struct { Name string `json:"name"` Email string `json:"email"` Age int `json:"age"` Address *Address `json:"address,omitempty"` // Pointer to Address struct }
  • Address *Address means the Address field is a pointer to an Address struct, not the actual struct itself.
  • The * in the struct definition does not dereference the pointer—it just defines the type as a pointer.

If Address is optional, use a pointer (*Address):

go
type User struct { Name string `json:"name"` Email string `json:"email"` Age int `json:"age"` Address *Address `json:"address,omitempty"` // Omits field if nil }

📌 Response when Address is nil

json
{ "name": "John Doe", "email": "john@example.com", "age": 30 }

No comments:

Post a Comment