Pointer Type variables in Go

 Pointer Type variables

Pointer variables holds the address of memory that holds the value of the variable


package main

import "fmt"

func main() {
    var name *string
    fmt.Println(name)
}

<nil> is go's terminology for an empty pointer object.


De-Referencing a pointer

As given below fmt.Println(*name) is de-referencing a pointer.

package main

import "fmt"

func main() {
    var name *string = new(string)
    *name = "Madhu"
    fmt.Println(*name)
}



package main

import "fmt"

func main() {
    name := "Madhu"
    deRef := &name
    fmt.Println(deRef, *deRef)
    name = "Tomy"
    fmt.Println(deRef, *deRef)
}

Here the name stores the value "Madhu", the variable deRef stores the address of the variable name or it is a pointer variable.

Now I change the value of name, the value of deRef variable also changes automatically.


No comments:

 Python Basics How to check the version of Python interpreter mac terminal

Popular in last 30 days