github.com/searKing/golang/go@v1.2.74/exp/slices/map.go (about)

     1  // Copyright 2022 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 slices
     6  
     7  import "fmt"
     8  
     9  // Map returns a slice mapped by format "%v" within all c in the slice.
    10  // Map does not modify the contents of the slice s; it creates a new slice.
    11  // TODO: accept [S ~[]E, E any, R ~[]M, M ~string] if go support template type deduction
    12  func Map[S ~[]E, E any, R []M, M string](s S) R {
    13  	return MapFunc(s, func(e E) M {
    14  		return M(fmt.Sprintf("%v", e))
    15  	})
    16  }
    17  
    18  // MapFunc returns a slice mapped by f(c) within all c in the slice.
    19  // MapFunc does not modify the contents of the slice s; it creates a new slice.
    20  // TODO: accept [S ~[]E, E any, R ~[]M, M any] if go support template type deduction
    21  func MapFunc[S ~[]E, E any, R []M, M any](s S, f func(E) M) R {
    22  	if s == nil {
    23  		return nil
    24  	}
    25  
    26  	var rr = make(R, len(s))
    27  	for i, v := range s {
    28  		rr[i] = f(v)
    29  	}
    30  	return rr
    31  }