13.8.15

Playing around with Golang Structs: Pointers, Functions, Variables, and methods

A few notes about structs in golang that might be tricky for a developer from another language to grasp.  Especially a language which doesn't use pointers...

Do you want to guess why I added the & ?

There are some important things to note here which can bite you in real world go programs, hence I've shown the DIFF rather than the entire program itself.  This diff fixes a bug.

1) Callbacks: Structs can declare functions as fields.  The LeaseGained and LeaseLost are examples of this. This is a way to implement callbacks.

2) Pointers: Nested structs behave quite differently depending on wether or not you declare them as pointers or not.  Be careful and make sure to use pointers if you want state to be shared between structs that you pass around.

3) Methods: structs are the mechanism for associating data with functions in Golang.  By declaring methods associated with a struct. 

No comments:

Post a Comment