Go Pointer Part II
By ski11up.com
In the previous blog-post Go Pointer Part I we have seen how we can use pointers
to update the value for a given struct
. There is little more left on that which we will cover here.
Go
Slice
is an exception and we can update the value of a slice with the index location but if we want to add more values to it then we need to use a pointer, let’s take a look at the same.
App
We will define a slice
of contacts, initialize the same and perform an update and append operation on the same.
Code
Go
code for updating contacts slice
.
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
29
30
package main
import "fmt"
type contacts []string (1)
func main() {
firstName := contacts{"John", "Jagdeep"} (2)
firstName.print()
update(firstName)
firstName.print()
firstName.appendTo("Pradeep")
firstName.print()
}
func update(c contacts) { (3)
c[0] = "Jagdeep"
}
func (c *contacts) appendTo(name string) { (4)
*c = append(*c, name)
}
func (c contacts) print() {
for _, name := range c {
fmt.Printf("\n%s ", name)
}
}
1 | defining contacts slice |
2 | initializing the slice |
3 | simply pass the index location and update the value |
4 | receiver function, we are passing a contact pointer and using the inbuilt method to append the new 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_slice.go
Notes
As you can see from the code that we have used index location to update the value of the contact slice but when we want to add more values to the slice then we have used pointers, this is an exception in Go
, rest all requires a pointer to update anything.