lo icon indicating copy to clipboard operation
lo copied to clipboard

Build a slice with length and default value

Open trsteel opened this issue 2 years ago • 0 comments

Is there anyway to build a slice like vector<int>(n, -1) in C++. length is n and fill it with -1. I use lo.Times(n, func(int) float64 { return -1 }) or lo.RepeatBy(n, func(int) float64 { return -1 }), but it looks not simple. Can we define a function like:

func MakeSlice[T any](n int, val T) []T {
    result := make([]T, 0, count)
    for i := 0; i < count; i++ {
        result = append(result, val)
    }
    return result
}

then use MakeSlice(n, -1).

trsteel avatar Jun 20 '23 12:06 trsteel