github.com/searKing/golang/go@v1.2.74/container/slice/foreach.go (about)

     1  // Copyright 2020 The searKing Author. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package slice
     6  
     7  import (
     8  	"sync"
     9  
    10  	"github.com/searKing/golang/go/util/object"
    11  )
    12  
    13  // ForEachFunc Performs an action for each element of this slice.
    14  // <p>The behavior of this operation is explicitly nondeterministic.
    15  // For parallel slice pipelines, this operation does <em>not</em>
    16  // guarantee to respect the encounter order of the slice, as doing so
    17  // would sacrifice the benefit of parallelism.  For any given element, the
    18  // action may be performed at whatever time and in whatever thread the
    19  // library chooses.  If the action accesses shared state, it is
    20  // responsible for providing the required synchronization.
    21  func ForEachFunc(s interface{}, f func(interface{})) {
    22  	forEachFunc(Of(s), f)
    23  }
    24  
    25  // forEachFunc is the same as ForEachFunc
    26  func forEachFunc(s []interface{}, f func(interface{})) {
    27  	object.RequireNonNil(s, "forEachFunc called on nil slice")
    28  	object.RequireNonNil(f, "forEachFunc called on nil callfn")
    29  	var wg sync.WaitGroup
    30  	for _, r := range s {
    31  		wg.Add(1)
    32  		go func(rr interface{}) {
    33  			defer wg.Done()
    34  			f(rr)
    35  		}(r)
    36  	}
    37  	wg.Wait()
    38  	return
    39  }