To use sync.OnceValue with a struct method, you need to store the sync.OnceValue function as a field in your struct. Here's how to do it:
package main
import (
"fmt"
"sync"
"time"
)
type MyService struct {
// Store the OnceValue function as a field
getExpensiveData func() string
}
// NewMyService creates a new service with the OnceValue initialized
func NewMyService() *MyService {
return &MyService{
getExpensiveData: sync.OnceValue(func() string {
// This expensive operation will only run once
fmt.Println("Computing expensive data...")
time.Sleep(2 * time.Second) // Simulate expensive work
return "expensive result"
}),
}
}
// GetData is a method that uses the OnceValue
func (s *MyService) GetData() string {
return s.getExpensiveData()
}
func main() {
service := NewMyService()
// First call - will compute the value
fmt.Println("First call:", service.GetData())
// Subsequent calls - will return cached value
fmt.Println("Second call:", service.GetData())
fmt.Println("Third call:", service.GetData())
}
If you want to initialize the OnceValue lazily (not in the constructor), you can use sync.OnceFunc to ensure the initialization happens only once:
type MyService struct {
getExpensiveData func() string
initOnce sync.Once
}
func (s *MyService) GetData() string {
s.initOnce.Do(func() {
s.getExpensiveData = sync.OnceValue(func() string {
fmt.Println("Computing expensive data...")
time.Sleep(2 * time.Second)
return "expensive result"
})
})
return s.getExpensiveData()
}
For cases where you need to pass parameters to the computation, you can create a closure:
type MyService struct {
cache map[string]func() string
mu sync.Mutex
}
func (s *MyService) GetDataForKey(key string) string {
s.mu.Lock()
if s.cache == nil {
s.cache = make(map[string]func() string)
}
if fn, exists := s.cache[key]; exists {
s.mu.Unlock()
return fn()
}
// Create a new OnceValue for this key
fn := sync.OnceValue(func() string {
fmt.Printf("Computing data for key: %s\n", key)
time.Sleep(1 * time.Second)
return fmt.Sprintf("result for %s", key)
})
s.cache[key] = fn
s.mu.Unlock()
return fn()
}
The key points are:
- Store the function returned by
sync.OnceValue as a struct field
- Initialize it either in the constructor or lazily on first use
- Call the stored function whenever you need the cached value