github.com/puzpuzpuz/xsync/v3@v3.1.1-0.20240225193106-cbe4ec1e954f/example_test.go (about)

     1  package xsync_test
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  
     7  	"github.com/puzpuzpuz/xsync/v3"
     8  )
     9  
    10  func ExampleMapOf_Compute() {
    11  	counts := xsync.NewMapOf[int, int]()
    12  
    13  	// Store a new value.
    14  	v, ok := counts.Compute(42, func(oldValue int, loaded bool) (newValue int, delete bool) {
    15  		// loaded is false here.
    16  		newValue = 42
    17  		delete = false
    18  		return
    19  	})
    20  	// v: 42, ok: true
    21  	fmt.Printf("v: %v, ok: %v\n", v, ok)
    22  
    23  	// Update an existing value.
    24  	v, ok = counts.Compute(42, func(oldValue int, loaded bool) (newValue int, delete bool) {
    25  		// loaded is true here.
    26  		newValue = oldValue + 42
    27  		delete = false
    28  		return
    29  	})
    30  	// v: 84, ok: true
    31  	fmt.Printf("v: %v, ok: %v\n", v, ok)
    32  
    33  	// Set a new value or keep the old value conditionally.
    34  	var oldVal int
    35  	minVal := 63
    36  	v, ok = counts.Compute(42, func(oldValue int, loaded bool) (newValue int, delete bool) {
    37  		oldVal = oldValue
    38  		if !loaded || oldValue < minVal {
    39  			newValue = minVal
    40  			delete = false
    41  			return
    42  		}
    43  		newValue = oldValue
    44  		delete = false
    45  		return
    46  	})
    47  	// v: 84, ok: true, oldVal: 84
    48  	fmt.Printf("v: %v, ok: %v, oldVal: %v\n", v, ok, oldVal)
    49  
    50  	// Delete an existing value.
    51  	v, ok = counts.Compute(42, func(oldValue int, loaded bool) (newValue int, delete bool) {
    52  		// loaded is true here.
    53  		delete = true
    54  		return
    55  	})
    56  	// v: 84, ok: false
    57  	fmt.Printf("v: %v, ok: %v\n", v, ok)
    58  
    59  	// Propagate an error from the compute function to the outer scope.
    60  	var err error
    61  	v, ok = counts.Compute(42, func(oldValue int, loaded bool) (newValue int, delete bool) {
    62  		if oldValue == 42 {
    63  			err = errors.New("something went wrong")
    64  			return 0, true // no need to create a key/value pair
    65  		}
    66  		newValue = 0
    67  		delete = false
    68  		return
    69  	})
    70  	fmt.Printf("err: %v\n", err)
    71  }