In golang, what is the difference between & and *

Issue

Can someone explain the difference between & and * in GO lang .. and provide examples of when & and * would be used to illustrate the difference?
From what I have read, they both relate to accessing a variables memory location however i’m not sure when to use & or *.

Solution

Here is a very simple example, that illustrates how & and * are used. Note that * can be used for two different things 1) to declare a variable to be a pointer 2) to dereference a pointer.

package main

import "fmt"

func main() {
    b := 6 

    var b_ptr *int // *int is used to declare variable
                   // b_ptr to be a pointer to an int

    b_ptr = &b     // b_ptr is assigned the value that is the
                   // address of where variable b is stored

    // Shorthand for the above two lines is:
    // b_ptr := &b

    fmt.Printf("address of b_ptr: %p\n", b_ptr)

    // We can use *b_ptr to get the value that is stored
    // at address b_ptr, known as dereferencing the pointer
    fmt.Printf("value stored at b_ptr: %d\n", *b_ptr)
    
}

Result:

address of b_ptr: 0xc82007c1f0
value stored at b_ptr: 6

Answered By – Akavall

Answer Checked By – Mildred Charles (GoLangFix Admin)

Leave a Reply

Your email address will not be published.