Hi gophers! In the last post I proposed a way to avoid I/O race on any global variable:
However, the code does not seem tidy, since each type needs to repeat defining the two methods Save and Load, though using this methods is easy.
So I did a little play around, but got stuck if I want to add in new methods to specific global types, such as tick to all integer types, or push to all slice types:
-------------------------------------------------------------
package main
import (
"fmt"
"sync"
)
type Global struct {
mutex sync.Mutex
value any
}
func (g *Global) Save(v any) {
g.mutex.Lock()
g.value = v
g.mutex.Unlock()
}
func (g *Global) Load() any {
g.mutex.Lock()
defer g.mutex.Unlock()
return g.value
}
var S = &Global{}
func main() {
S.Save(5)
fmt.Printf("S=%v, S.mutex=%v, S.value=%d \n", S, S.mutex, S.value)
fmt.Printf("S=%v, S type as %[1]T", S.Load())
}
//New global types that has methods beyond Save and Load:
/*
type countable interface {
~int | ~int8 | ~int16 | ~int32 | ~int64
}
type Counter struct {
mutex sync.Mutex
value countable
}
func (c *Counter) Tick() {
c.mutex.Lock()
c.value += 1
c.mutex.Unlock()
}
*/
=====================================
It worked well with the "Global" struct type.
However, as I want to narrow the scope of this type down to generate integer types (as in the commented code), it encountered two obstacles:
1) It is not legal to embed a generic inside a struct, nor can it make generalized computation =+1
2) Inheritance is not available in golang, so type "Counter" cannot inherit type "Global" and get its methods automatically. I need to repeat Save and Load methods to "Counter".
Am I correct? Or can you improve it?