Created
April 29, 2021 02:56
-
-
Save drbh/4650a7c4da05a4a7f9891cd9f0d32d5f to your computer and use it in GitHub Desktop.
Showing the importance of using pointer receivers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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