Skip to content

A learning repo to explain the difference using pointer and non-pointer receivers

License

Notifications You must be signed in to change notification settings

mikebharris/understandinggoreceivers

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Understanding Go Receivers and their constructs

I had confused myself about using Receivers and the difference between using pointer receivers and non-pointer receivers in different types of context.

This could have been easily solved by me re-reading pages 158-159 of The Go Programming Language by Donovan and Kernighan, but I'd got myself into a programming pickle and had forgotten to go back to basics.

I finally did and with the help of @hoegrammer, we worked it out by making a simple coding example that tested our assumptions.

This reminded me that it's always the best thing to do: go back to basics and check one's assumptions.

In this example, we have a container for a thing. The thing can be of various types, and therefore the container can be of various types of thing container. Each type of thing container implements the RunnableThingContainer interface, which means that the thing containers must implement the Run() method.

We then have a Box of these thing containers and we call the Run() method on each of the things in the containers in the box.

In one example the Box uses pointer receivers, meaning that the operations we do act on the things pointed to, which amount to the instances of the things declared in the test. This leads us towards a more classic OO-style as implemented in languages like Java:

boxOfThingContainersUsingPointerReceivers := BoxOfThingContainersUsingPointerReceivers{}
boxOfThingContainersUsingPointerReceivers.AddThingContainer(&integerContainer)
boxOfThingContainersUsingPointerReceivers.AddThingContainer(&runeContainer)
boxOfThingContainersUsingPointerReceivers.RunThings()

In the other example, the Box uses non-pointer receivers, meaning that the operations we do act on copies of the things declared in the tests. We therefore need to return copies of the things at the end of the methods, which leads us towards a more functional programming style as written in languages like JavaScript:

BoxOfThingContainers{}.
    AddThingContainer(&integerContainer).
    AddThingContainer(&runeContainer).
    RunThings()

About

A learning repo to explain the difference using pointer and non-pointer receivers

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages