To change the value of a variable using a pointer in Go or Golang, you can use the *
symbol (asterisk) followed by the name of the pointer variable that points to the memory address of the variable that you need to change the value of. After that, you can assign any value to it using the =
operator (assignment), and then that value will be assigned to the original variable. This is called pointer dereferencing in Go.
TL;DR
package main
import "fmt"
func main() {
// a simple variable
role := "Admin"
// get the memory address of the `role` variable
roleMemAddr := &role
// assign the value of `Employee` to the `role` variable
// using the `roleMemAddr` pointer variable and dereferencing
// it using the `*` symbol to assign the new value
*roleMemAddr = "Employee"
// log the value of `role` variable to console
fmt.Println(role) // Employee ✅
}
For example, let's say we have a variable called role
having the string
type value of Admin
like this,
package main
func main(){
// a simple variable
role := "Admin"
}
Now let's make a pointer variable to hold the memory address of the role
variable.
It can be done like this,
package main
func main(){
// a simple variable
role := "Admin"
// get the memory address of the `role` variable
roleMemAddr := &role
}
To know more about getting the memory address of a variable see the blog on How to get the memory address of a variable in Go or Golang?.
We aim to change the value of the original role
variable to the string
type value of Employee
, using the roleMemAddr
pointer variable. To do that we can use the *
symbol followed by the roleMemAddr
pointer variable name and then use the =
operator to assign the string
type value of Employee
. This technique is called pointer dereferencing.
It can be done like this,
package main
func main() {
// a simple variable
role := "Admin"
// get the memory address of the `role` variable
roleMemAddr := &role
// assign the value of `Employee` to the `role` variable
// using the `roleMemAddr` pointer variable and dereferencing
// it using the `*` symbol to assign the new value
*roleMemAddr = "Employee"
}
Finally to check if the original role
variable's value has changed or not, let's log the value of that to the console like this,
package main
import "fmt"
func main() {
// a simple variable
role := "Admin"
// get the memory address of the `role` variable
roleMemAddr := &role
// assign the value of `Employee` to the `role` variable
// using the `roleMemAddr` pointer variable and dereferencing
// it using the `*` symbol to assign the new value
*roleMemAddr = "Employee"
// log the value of `role` variable to console
fmt.Println(role) // Employee ✅
}
As you can see that we have successfully changed the value of a variable using a pointer variable in Go. Yay 🥳!
See the above code live in The Go Playground.
That's all 😃.