Search code examples
arraysgoslice

Default all values in a new slice to a custom value GoLang


Is it possible to define a custom default value when creating a slice in Go ?

For example

manyFlags := make([]int, 10)
manyEmptyFlags := make([]int, 10, 10)
someEmptyFlags := make([]int, 5, 10)

manyFlags would create an empty slice with capacity 10

manyEmptyFlags would create a slice with length 10 but all values are Zero

someEmptyFlags would create a slice with capacity 10 and length 5 with Zero for the first 5 values

Would it be possible to have a set default value like 1 or -1 ?

I can loop through and set the value or change my program to treat zero as the default value but is there really no other way ?


Solution

  • Would it be possible to have a set default value like 1 or -1 ?

    No.

    I can loop through and set the value or change my program to treat zero as the default value but is there really no other way ?

    Yes. (there is no other way).

    General rule of thumb: There is no magic in Go.