Go Pointer Part I
By ski11up.com
Go lang is an open-source programming language like C, having pointers and not strongly typed language. And most importantly it is not an Object Oriented Programming(debatable) language though it has likes of defining packages
and interfaces
like Java
.
Let’s explore the Go
pointers
in this post.
Pass By Reference
Go
follows pass by reference. Slice
is an exception where we can use the index to update value, we will discuss it in the next post. To update a value of a given variable we need to get the handle of the memory reference and then we can update the values, this is called pass by reference. If we just use the pass by value, Go
will make a copy of the variable and perform the update operation. So we are not updating the actual variable instead of a copy of the variable. To update the actual variable we need to use pointers
.
App
We will define a struct
, initialize it and try to update the value of its one of the name/key.
struct
will be Contact having firstName, and lastName.
We will first try to update with a pass by value and then pass by reference.
Code
Go
code for updating Contact.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package main
import "fmt"
type Contact struct { (1)
FirstName string
LastName string
}
func main() {
contactDetails := Contact{ (2)
FirstName: "John",
LastName: "Doe",
}
contactDetails.print()
updateContact(&contactDetails) (3)
contactDetails.print()
}
func updateContact(c *Contact) { (4)
c.FirstName = "Jagdeep"
c.LastName = "Jain"
}
func (c Contact) print() {
fmt.Printf("\nContact Details # %v", c)
}
1 | defining Contact struct |
2 | initializing the Contact with values |
3 | passing the address location of the Contact |
4 | updating the Contact |
restrict using pointers only when you want to perform the update operation |
Execute Go App
Navigate to the project folder and execute the below command.
$ go run update_contact.go
Notes
As you can see from the code that we have used &
for passing the address location the pointer and for the update function argument we are using *
for making that argument as the pointer.
Exercise
Remove the`&`` and *
from the code and run the app again, you will find that the Contact values are not getting updated and they still have the old values, this is where we need pass by reference rather pass by value.
Next
Go to Go Pointer Part II to know more about Pointers
usage in Slice
.