0

I have a struct defined as shown below :

type abc struct {
  srcName string
  destName string
  flag    bool  'default:false'
}

In my code , i initialize it with make function

var abcList []abc

func init() {
    abcList = make([]abc, 1)
}

func main() {
 var abcElem abc

 abc.srcName = "src"
 abc.destName = "dest"
 abc.flag  = true

 abcList = append(abcList, abc)

 klog.Info("abcList:", abcList)
}

I see the output as:

abcList: [{    false} {"src", "dest", true}]

Want to know why slice element with default value is added. Isn't it a wrong thing? If i initialize this slice with bigger capacity, then i see many such elements with default value. It adds extra cost while iterating this slice.

  • 1
    The expression `make([]abc, 1)` creates a slice with a single element set to the zero value. Fix the code by removing the line of code. The `append` function handles a nil slice argument. There are many other errors in the code. – Charlie Tumahai Nov 04 '20 at 07:12
  • check the go tour https://tour.golang.org/moretypes/11 and others SO answers https://stackoverflow.com/questions/36683911/go-slices-capacity-length –  Nov 04 '20 at 10:27
  • Incidentally this particular mistake—calling `make` with a nonzero initial size when what you had intended is a nonzero initial *capacity* instead—is a common one for those new to Go, used to other languages that require an initial capacity. – torek Nov 05 '20 at 18:39

4 Answers4

1

You need to do:

make([]abc, 0, 1)

The 2nd argument is count for slices, third is the capacity.

If you initialize a slice with s := make([]abc, 1) it will contain one empty element. You can overwrite that element with s[0] = xyz. If you append to the slice, the empty element(s) will stay and new elements will be added.

Note: The init function is not needed here. You can just do:

// package level declaration
var abcList = make([]abc, 0, 1)
TehSphinX
  • 6,536
  • 1
  • 24
  • 34
Alexander Trakhimenok
  • 6,019
  • 2
  • 27
  • 52
0

The go make([]abc, 1) has length set to 1. To understand it, the go syntax for array initialization is

make([]array, length, capacity)

Where a new array of size length is created and initialized, which can be extended upto capacity. In your case length=1 means, create an array of type []abc and initialize one element with default values. The capacity was not present which means capacity=n

You can avoid the default value initialization by,

make([]abc, 0, <1...n>)

or

abcList = []abc{}
0

make([]abc, 0, 1) or just use only var abcList []abc don't initilize with make

-1

I don't see where the init code is called. The above code something you must have missed when posting this question. You are not invoking init() anywhere in main()

The init function is unncessary since you are using append in the main() function.

cslrnr
  • 694
  • 1
  • 8
  • 24