Created
May 1, 2024 18:32
-
-
Save abdivasiyev/d26b3bb1a6391c2dbe3220d4630ad838 to your computer and use it in GitHub Desktop.
Set value by calling functions in generics
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 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