gitee.com/sy_183/go-common@v1.0.5-0.20231205030221-958cfe129b47/component/pointer.go (about)

     1  package component
     2  
     3  import "sync"
     4  
     5  type Pointer[E any] struct {
     6  	Init        func() *E
     7  	initializer sync.Once
     8  	elem        *E
     9  }
    10  
    11  func NewPointer[E any](init func() *E) *Pointer[E] {
    12  	return &Pointer[E]{Init: init}
    13  }
    14  
    15  func (c *Pointer[E]) Get() *E {
    16  	if c.elem != nil {
    17  		return c.elem
    18  	}
    19  	c.initializer.Do(func() {
    20  		c.elem = c.Init()
    21  	})
    22  	return c.elem
    23  }