Pointers are not the Devil’s tools
Oh, wait, if you have never heard of pointers or stumbled upon a usage before now, this post is for you!
If you happen to have heard of pointers prior to this (maybe C++ or C) and still don’t understand it. This post is even better for you.
According to Wikipedia “ a pointer is a programming language object, whose value refers to (or “points to”) another value stored elsewhere in the computer memory using its memory address.” A simpler definition is that a pointer is a value which points to the address of another.
I will walk you through some practical examples using Go(a bit bias here) which should clear the air. Let’s get straight into it!
Why do we even need them in the first place? They are pretty useful as listed below:
- To assign a variable from another function
- To modify a variable from a member function
- To manage copy on function call
Nevertheless, pointers are hard to debug when things go crazy. Any function that holds reference to the pointer can modify it and “you know the rest”
Take a look at this program and the images that explain it;
func main() {
a := 200
b := &a
*b++
fmt.Println(a)
}
I mentioned three points as to the usefulness of pointers earlier on but I will discuss two here, the third will be another post of his own :)
- To assign a variable from another function
func reset(value int) {
value = 0
}
func resetPtr(value *int) {
*value = 0
}
func main() {
value := 1
fmt.Println("initial", value)
reset(value)
fmt.Println("after reset", value)
resetPtr(&value)
fmt.Println("after resetPtr", value)
}
OUTPUT
2. To modify a variable from a member function
type MyType struct {
value int
name string
}
func (mt *MyType) reset() {
mt.value = 0
mt.name = "Dummy reset name"
}
func (mt *MyType) resetPtr() {
mt.value = 9
mt.name = "Dummy pointer reset name"
}
func main() {
mt := MyType{
value: 1,
name: "Sample",
}
fmt.Println("Initial name ", mt.name, mt.value)
mt.reset()
fmt.Println("After reset() is called ", mt.name, mt.value)
mt.resetPtr()
fmt.Println("After resetPointer() with pointer ", mt.name, mt.value)
}
OUTPUT
Taking a look at each program and the corresponding output, I hope you get to understand how they are modified.
If there’s anything you’d like to see written on this, kindly drop in the comments.