Instagram
youtube
Facebook
Twitter

Address and Pointers in Golang

Address and Pointers

  • Go is fast because of its pass-by-value feature i.e. when we call a function with an argument the go compiler simply uses the value of the argument rather than the parameter itself. That means the changes in the functions will remain inside the function.
  • The address is the technical term used in computer science when a compiler is allocating some space in its memory and each address is unique with hexadecimal values which is a way to represent 1 digit values and to find the address of a variable we use & operator.
func main() {

  treasure := "The friend we make along the way."

  fmt.Println(&treasure) //outputs 0xc000010230

}
  • Pointers are those variables that store addresses for us and the syntax to declare pointers is

    var pointerForInt *int

Dereferencing

  • In Dereferencing we can change the value of the pointer while having the same address let's follow this code snippet.
  • Here, we use pointerForStr variable to store the address of the lyrics variable and then we used * operator to change the value at that address our pointer is pointing to i.e. lyrics.
lyrics := "Moments so dear"

pointerForStr := &lyrics

*pointerForSter = "Journeys to plan"

fmt.Println(lyrics) //prints journeys to plan

With this we can approach the problem of changing values of the variable in different scope

  • Lets us understand this problem in more context firstly, understand this code snippet.

    func addHundred(num int) {
    
      num += 100
    
    }
    
    func main() {
    
      x := 1
    
      addHundred(x)
    
      fmt.Println(x) //prints 1
    
    }

    We can see that the value of x is not changing even though the function addHundred is doing fine this is because we know that Go is a pass-by-value language which only and In order to change the value of our variable x we need to provide the address and store the value there this is where pointers and address come into the picture.

    func addHundred (numPtr *int) {
    
      *numPtr += 100
    
    }

    Here we’re providing the pointer to the input of our function and hence we are passing the value of the pointer which is an address and there we are dereferencing the value of the pointer and adding 100 to it.

    func addHundred (numPtr *int) {
    
      *numPtr += 100
    
    }
    
    func main() {
    
      x := 1
    
      addHundred(&x)
    
      fmt.Println(x) ..prints 101
    
    }

    Now our code works fine!