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.