Skip to content

Instantly share code, notes, and snippets.

@abdivasiyev
Created May 1, 2024 18:32
Show Gist options
  • Save abdivasiyev/d26b3bb1a6391c2dbe3220d4630ad838 to your computer and use it in GitHub Desktop.
Save abdivasiyev/d26b3bb1a6391c2dbe3220d4630ad838 to your computer and use it in GitHub Desktop.
Set value by calling functions in generics
package main
import "fmt"
type Setter[V any] interface {
Set(value V)
}
type Getter[V any] interface {
Get() V
}
type SetGetter[K any, V any] interface {
Setter[V]
Getter[V]
*K
}
func Process[K any, V any, _K SetGetter[K, V]](k K, value V) K {
var _k = _K(&k)
_k.Set(value)
return k
}
type Counter struct {
value int
}
func (c *Counter) Set(value int) {
c.value += value
}
func (c *Counter) Get() int {
return c.value
}
func main() {
var c Counter
for i := range 10 {
c = Process(c, i)
fmt.Println(c.Get())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment