6

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

manyFlags 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 ?

Saurabh
  • 5,176
  • 4
  • 32
  • 46
smehnawal
  • 553
  • 1
  • 7
  • 16
  • Does this answer your question? [Is it possible to initialize slice with specific values?](https://stackoverflow.com/questions/39984957/is-it-possible-to-initialize-slice-with-specific-values) – Puneet Singh May 15 '20 at 12:19
  • 3
    Write a helper function that does this for you. See [Is there analog of memset in go?](https://stackoverflow.com/questions/30614165/is-there-analog-of-memset-in-go/30614594#30614594) – icza May 15 '20 at 13:12

1 Answers1

14

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.

Volker
  • 40,468
  • 7
  • 81
  • 87