gitee.com/sy_183/go-common@v1.0.5-0.20231205030221-958cfe129b47/component/elem.go (about) 1 package component 2 3 import "sync" 4 5 type Elem[E any] struct { 6 Init func() E 7 initializer sync.Once 8 done bool 9 elem E 10 } 11 12 func NewElem[E any](init func() E) *Elem[E] { 13 return &Elem[E]{Init: init} 14 } 15 16 func (c *Elem[E]) Get() E { 17 if c.done { 18 return c.elem 19 } 20 c.initializer.Do(func() { 21 c.elem = c.Init() 22 c.done = true 23 }) 24 return c.elem 25 }