1
2
3
4
5
6
7
8
9 package main
10
11 import (
12 "fmt"
13 "sync"
14 )
15
16 type MyStruct[T any] struct {
17 val T
18 }
19
20 type Lockable[T any] struct {
21 MyStruct[T]
22 mu sync.Mutex
23 }
24
25
26 func (l *Lockable[T]) Get() T {
27 l.mu.Lock()
28 defer l.mu.Unlock()
29 return l.MyStruct.val
30 }
31
32
33 func (l *Lockable[T]) Set(v T) {
34 l.mu.Lock()
35 defer l.mu.Unlock()
36 l.MyStruct = MyStruct[T]{v}
37 }
38
39 func main() {
40 var li Lockable[int]
41
42 li.Set(5)
43 if got, want := li.Get(), 5; got != want {
44 panic(fmt.Sprintf("got %d, want %d", got, want))
45 }
46 }
47
View as plain text