In this lesson, we’ll explore how to pass variables by reference in functions using Golang pointers. Unlike passing by value, where a copy of the variable is sent to the function, passing by reference allows a function to modify the original variable by using its address. Golang supports pointers, which let you pass the memory address of a variable to a function. When you pass a pointer, any changes made inside the function affect the original variable. For example, consider a variable “a” created in the main function. When we call the function modify, we pass the address of “a”. Inside the modify function, dereferencing the pointer updates the original variable. In the following example, if “a” is modified from “hello” to “world”, the change is visible after the function call. Below is the complete code demonstrating this concept:Documentation Index
Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
Use this file to discover all available pages before exploring further.
In the example above:
- A string variable “a” is initialized with “hello”.
- Passing
&asends the address of “a” to themodifyfunction. - Inside the function, dereferencing the pointer (
*s) updates the value. - The modified value is printed after the function call.
Slices Example
Consider the following example where we update a slice:A slice in Go is a reference type. When you pass the slice to a function, it points to the same underlying array. Hence, changes inside the function are reflected in the original slice.
Maps Example
Maps in Go also behave as reference types. When you pass a map to a function, any changes made to the map inside the function will affect the original map. Here’s an example:In the above example:
- A map named
ascii_codesis created with key-value pairs. - The
modifyfunction adds a new key “K” with the value 75. - The changes are visible after running the function, confirming that maps are passed by reference.