1
2
3
4
5
6
7 package main
8
9 import "sync"
10
11
12
13 type Lockable[T any] struct {
14 x T
15 mu sync.Mutex
16 }
17
18
19 func (l *Lockable[T]) get() T {
20 l.mu.Lock()
21 defer l.mu.Unlock()
22 return l.x
23 }
24
25
26 func (l *Lockable[T]) set(v T) {
27 l.mu.Lock()
28 defer l.mu.Unlock()
29 l.x = v
30 }
31
32 func main() {
33 sl := Lockable[string]{x: "a"}
34 if got := sl.get(); got != "a" {
35 panic(got)
36 }
37 sl.set("b")
38 if got := sl.get(); got != "b" {
39 panic(got)
40 }
41
42 il := Lockable[int]{x: 1}
43 if got := il.get(); got != 1 {
44 panic(got)
45 }
46 il.set(2)
47 if got := il.get(); got != 2 {
48 panic(got)
49 }
50 }
51
View as plain text