Last active
October 6, 2023 17:13
-
-
Save ozline/59287f955fffa3bada90eb883e53dc67 to your computer and use it in GitHub Desktop.
A small example about callback function management.
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" | |
"sync" | |
) | |
var ( | |
callback map[string]func() | |
mu sync.Mutex | |
) | |
func main() { | |
Register(foo1, "foo1") | |
Register(foo2, "foo2") | |
if err := Deregister("foo1"); err != nil { | |
panic(err) | |
} | |
for _, f := range callback { | |
f() | |
} | |
} | |
func Register(fun func(), key string) { | |
mu.Lock() | |
defer mu.Unlock() | |
if callback == nil { | |
callback = make(map[string]func()) | |
} | |
callback[key] = fun | |
} | |
func Deregister(key string) error { | |
mu.Lock() | |
defer mu.Unlock() | |
if _, exists := callback[key]; !exists { | |
return fmt.Errorf("callback %s not registered", key) | |
} | |
delete(callback, key) | |
return nil | |
} | |
func foo1() { fmt.Println("foo1") } | |
func foo2() { fmt.Println("foo2") } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment