Skip to content
The Chat Archive
claude-3-5-sonnet-20241022· Anthropic LMArena Human Preference 140K

How do I make a struct function use sync.OnceValue?

  1. User

    How do I make a struct function use sync.OnceValue?

  2. Assistant

    I'll show you how to use sync.OnceValue with a struct function in Go. Here's a simple example:

    type MyStruct struct {
        data string
    }
    
    func (m *MyStruct) ExpensiveOperation() string {
        getValue := sync.OnceValue(func() string {
            // This will only be executed once
            return "expensive computation with " + m.data
        })
        
        return getValue()
    }
    

    The key points are:

    1. sync.OnceValue takes a function that returns a value
    2. It returns a function that you can call repeatedly
    3. The initialization function only runs once, and subsequent calls return the cached value

    Here's a more complete example showing how it works:

    type Cache struct {
        data string
    }
    
    func (c *Cache) GetValue() string {
        getValue := sync.OnceValue(func() string {
            // Simulate expensive operation
            time.Sleep(time.Second)
            return "processed: " + c.data
        })
        
        // This will only compute the value once, then cache it
        return getValue()
    }
    
    func main() {
        cache := &Cache{data: "test"}
        
        // First call will take 1 second
        fmt.Println(cache.GetValue())
        
        // Second call will be instant
        fmt.Println(cache.GetValue())
    }
    

    This is particularly useful when you have expensive computations that you want to perform lazily and cache the result.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.