github.com/fufuok/utils@v1.0.10/xsync/example_test.go (about)

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