Following from my previous
post about everything being passed by value to a function, its time to think about the following scenario.
1. I create a function that takes a pointer which is pointing to nil.
2. I do something in the function such that pointer starts pointing to an object.
3. When I access the pointer outside the function (after the function has run) the pointer is still facing to nil. What the heck?
package main
import (
"fmt"
)
type element struct {
name string
}
func main() {
var e *element
NameIt(e, "gold")
fmt.Println(e) // Prints: 'nil'}
func NameIt(c_e *element, s string) {
if c_e == nil {
c_e = &element{name: s}
}
c_e.name = s
}
This is exactly due to the reason mentioned in my previous
post. When the pointer 'e' is passed to the function 'NameIt', its pointing to 'nil'. The function creates a copy 'c_e' which is also pointing to 'nil' but then creates a new object of type 'element' and makes c_e point to the new element.
Note that the original pointer 'e' is still pointing to nil. The function returns and the original pointer 'e' has not changed. So what to do in cases where you want your passed pointer to behave as you expect. The following the correct way of doing it.
func main() {
var e *element
if e == nil {
e = &element{} // Ensure that you do not
// pass nil pointers to a function.
}
NameIt(e, "gold") // Prints '&{gold}'
fmt.Println(e)
}
Always pass pointers that point to a valid reference than a 'nil', if you expect them to change later in a function.
Comments positive or negative are more than welcome.