Skip to content

Instantly share code, notes, and snippets.

@drbh
Created April 29, 2021 02:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drbh/4650a7c4da05a4a7f9891cd9f0d32d5f to your computer and use it in GitHub Desktop.
Save drbh/4650a7c4da05a4a7f9891cd9f0d32d5f to your computer and use it in GitHub Desktop.
Showing the importance of using pointer receivers
package main
import (
"fmt"
)
type Item struct {
TestChan chan int64
}
func (i Item) Tick() {
i.TestChan <- int64(10)
}
// !!! WARNING THIS FUNCTION WILL NOT WORK !!!
// func (i Item) Subscribe(myChannel chan int64) {
// i.TestChan = myChannel
// }
// The issue was a missing *
// The reciever Item should be a pointer reciever
// "Methods with pointer receivers can modify the
// value to which the receiver points"
// https://tour.golang.org/methods/4
func (i *Item) Subscribe(myChannel chan int64) {
i.TestChan = myChannel
}
func main() {
tickDataChannel := make(chan int64)
customItem := Item{
TestChan: nil,
}
// should set the channel on the customItem
// this will fail to update the value if the
// reciever isn't a pointer reciever
customItem.Subscribe(tickDataChannel)
// run the Tick method to send data down chan
go customItem.Tick()
data := <-tickDataChannel
fmt.Println(data)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment