github.com/sohaha/zlsgo@v1.7.13-0.20240501141223-10dd1a906f76/zutil/once.go (about) 1 //go:build go1.18 2 // +build go1.18 3 4 package zutil 5 6 import ( 7 "sync" 8 "time" 9 ) 10 11 // Once initialize the singleton 12 func Once[T any](fn func() T) func() T { 13 var ( 14 once sync.Once 15 ivar T 16 ) 17 return func() T { 18 once.Do(func() { 19 err := TryCatch(func() error { 20 ivar = fn() 21 return nil 22 }) 23 if err != nil { 24 go func() { 25 time.Sleep(time.Second) 26 once = sync.Once{} 27 }() 28 } 29 }) 30 31 return ivar 32 } 33 }