You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
package main
import (
"fmt""sync""time"
)
typeLockable[Tany] struct {
mu sync.MutexvalueT
}
// Do calls [f] and then returns the latest value in [Lockable] and any error from calling [f].// Note: even where [f] returns an error the returned [value] may not be the zero value. It will be the latest value in [Lockable]func (l*Lockable[T]) Do(
ffunc(l*Lockable[T]) error,
) (valueT, _error) {
l.mu.Lock()
err:=f(l)
val:=l.value// read only after calling fl.mu.Unlock()
returnval, err
}
funcNew[Tany](valueT) *Lockable[T] {
return&Lockable[T]{value: value}
}
varlog=New(0)
funcmain() {
fmt.Println("val: ", log.value)
val, err:=log.Do(
func(l*Lockable[int]) error {
l.value=34returnnil
},
)
iferr!=nil {
panic(err)
}
fmt.Println("val: ", val)
fori:=range19 {
gofunc(iiint) {
val, err:=log.Do(
func(l*Lockable[int]) error {
l.value=iireturnnil
},
)
iferr!=nil {
panic(err)
}
fmt.Println("ii: ", ii, "val: ", val)
}(i)
}
time.Sleep(2*time.Second)
}
https://github.com/func25/go-practical-tips/blob/main/tips.md#making-a-type-with-built-in-locking-syncmutex-embedding
The text was updated successfully, but these errors were encountered: