In golang, what is the difference between & and *

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)