Easy to do and hard to fix pointer mistakes in Go

I will be writing about some very easy to make mistakes in Golang and which can be very hard to debug without verbose unit testing. 

1. Forgetting pointer (*) when to associate a method with a structure.

It will work on a copy if pointer is not given. Compiler won’t check it. And as you just call s.Super(), you cannot force passing pointer at all. So, your structure variable’s members won’t get modified in the structure function!


type Saiyan struct {

   Name string

   Power int

}

func (s Saiyan) Super() {

   s.Power += 10000

}

So, always be careful. It’s better to follow a convention that all struct methods can modify the struct itself. If a method works on a copy, let it be a non-struct method.


func (s *Saiyan) Super() {

   s.Power += 10000

}

2. Forgetting passing pointers to functions

I am attaching a code sample from “The little go book” by Karl Seguin.


func main() {

	goku := &Fighter {

		name: "Goku",

		power: 2000,

	}

	Ulti(goku)

}

func Ulti(f *Fighter) {

	f.power += 10000

}

Now when you write a lot of codes, when you instantiate structs with both value and pointers (goku := &Fighter, or goku := Fighter) in different places, it’s very easy to make a mistake to pass a pointer to a function where needed, as you are calling Ulti(goku). You can no way tell whether you are passing a reference or value at line Ulti(goku). A good convention would be never instantiate with pointer address and always pass reference like Ulti(&goku). No matter wherever you are calling the function, you can be always sure whether you are passing a value or a pointer. So, better code like


func main() {

	goku := Fighter { //always assign values, not pointers

		name: "Goku",

		power: 2000,

	}

	Ulti(&goku) //always pass pointer like this

}


But if you need complex structures with a lot of pointers, you can have another convention that I am following. For pointers, use p as a prefix like (pGoku when I am having a pointer) or just always use pointers if not immutable and use im as a prefix for immutable instances.

to be continued…

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s