Pointers

They pass the reference to value rather than the value itself, this helps to passing a copy of the value rather than the value itself.

Important:

& : to get memory address of value * : to extract value from memory address (if not assigned to a value) but if its variable with * is assigned to a value, this is called dereference

// simple example to demonstrate pointer usage

package main

import (
    
    "fmt"
    
)

func main() {

    // a variable containing data
    a := 45
    
    // assign it through pointer
    // this b is not pointing to a but it takes mem address of block memory
    // where 45 is stored.

    b := &a // now both has access to share space of mem
    *b = 56  // assign another value to b
    
    
    fmt.Println(a, *b) // print a and b  
    
    // (note we did not use * with a because it was assigned a value initially
    // but b was referenced
    
    c := a  // Just assign a to another var c
    // here it will pass the value and not address
    
    c = 34
    
    fmt.Println(a, c)  // you will notice no change in a     
    
}

In a programming language, pass by value and pass by reference are two general argument passing method. The difference is that, pass by value is passing a copy of variable or value while pass by reference is passing the reference to memory address where the value resides. This means, any variable that is referenced to the shared memory space will alter the value and the effect will be visible in all variables that references the address.

There are various example where you can use Pointers:

  1. You will need to use Pointer when developing banking application that brings change in account balance when you add / remove amount

  2. You will need both with and without Pointer in performing transaction (a transaction involves simulataneous credit and debit from two different accounts)

package main

import (
    "fmt"
)

without_ptr(i int){ // int type
    fmt.Println(i)
    i = 0
}

with_ptr(i *int){ // *int type
    fmt.Println(*i) // printing pointer value
    *i = 2 // dereferencing
}

func main() int{

    ptr := 1
    without_ptr(ptr)
    fmt.Println(ptr)

    ptr2 := 2
    with_ptr(*ptr2)
    fmt.Println(&ptr2)
}

You can use pointer with struct, Methods, interfaceetc. You will often find use of Pointers in Go which is only to pass reference to value (address of value).

Last updated

Was this helpful?