Slices created with make() - append creates an empty entry based on the length value provided

str_slice := make([]string, 1)
str_slice = append(str_slice, “X”)
str_slice = append(str_slice, “Y”)
str_slice = append(str_slice, “Z”)

for _, val := range str_slice {
	anyThing = append(anyThing, val)
}

fmt.Println(anyThing)

len(str_slice) = 4. We don’t have this issue with len attire set to 0 in make()

When appending, can’t it detect automatically that it s empty and place in first position ? Any proposal to change this behaviour in latest go version ?

after
str_slice := make([]string,1)
the slice isn’t empty: it has one entry with the “zero” value of “” for a string.
if you want an empty slice, try
str_slice := make([]string, 0, 1)
Jonathan.

Yes. Makes sense thats why i mentioned if len=0 in make() its different.
Go initialise with default value of that type. ( different from C)
What I was trying to point out is, when append is made why can’t it over write the first “” entry and make X as its first entry.

Because that element might be "" on purpose, also checking if it is the random value has a runtime cost, which wouldn’t be wanted by some.

If you want to overwrite previous entries that appear to be empty by your definition of empty, you need to add your own append function.

Its because its complied language. initialisation should make a default value entry for this slice with the type of data it holds.
Coming from python background i thought of this - which happens dynamically at runtime.
listString = []
listString.append("abc)
listString.append("xyz)
print(listString)
–> [“abc”, “xyz”]

Makes sense. It has runtime cost.

Thanks @jonoke and @NobbZ

listString = [] in python is not equivalent to listString = make([]string, 1), but much more like listString = make([]string, 0).

listString = make([]string, 1) in go is more equivalent to listString = [""] in python.

This has nothing to do with beeing a compiled language or not.

2 Likes

If I was trying to match your Python code as closely in Go as I could, I would write it like this:

listString := []string{}
listString = append(listString, "abc")
listString = append(listString, "xyz")
fmt.Println(listString)
2 Likes

Thanks @skillian