💻 Tech
Idempotency in Go can be achieved with sync package.
This codes outputs “Playing…” twice. What we want to achieve is to only output it once regardless of how many times Play() is called.
func main() {
p := Player{}
p.Play()
p.Play()
}
func (p *Player) Play() {
fmt.Println("Playing...")
}
This version only outputs “Playing…” once because of sync.Once.
func main() {
p := Player{}
p.Play()
p.Play()
}
type Player struct {
once sync.Once
}
func (*Player) play() {
fmt.Println("Playing...")
}
func (p *Player) Play() {
p.once.Do(p.play)
}