有没有更好的方法来处理可变大小的切片?

please see the code below

names := make([]string, 0, 100)
names = append(names, "Jack")
names = append(names, "Jacob")
// adding many names in here

Given a circumstances like this: I will get these names from somewhere else, before that I didn't know the size of it. So I a need a dynamic array to contains these names. The above code is way that I came up with. I was wonder if there is any more elegant way to do this.

If I initialise like this

names := make([]string, 100, 200)
// then I use append in here
// I would get first 100 elements as empty, the append start at index 101.

I suppose this would be a such waste on memory. I am totally new to static programming language, so if there is any wrong concept in this post, please point it out.

Just only declare the type and then assign the appended slice to it:

package main

import "fmt"

func main() {
    var names []string
    names = append(names, "foo")
    names = append(names, "bar")
    fmt.Println(names)
}

Yields:

>> [foo bar]

If you are into the mechanics of it, here is a nice blog post.

You can consider setting an initial length, instead of '0', in addition of your capacity (100, meaning at most 100 elements can be added).

See "Arrays, slices (and strings): The mechanics of 'append'"

allocation.

We could use the new built-in function to allocate a bigger array and then slice the result, but it is simpler to use the make built-in function instead.
It allocates a new array and creates a slice header to describe it, all at once. The make function takes three arguments: the type of the slice, its initial length, and its capacity, which is the length of the array that make allocates to hold the slice data

The idea is to avoid append() to have to grow the slice too soon, especially if you know you will receive at least n elements.

Stick with what you are doing. The 100 DOES NOT prevent the slice from having more the 100 elements

names := make([]string, 0, 100)
names = append(names, "Jack")
names = append(names, "Jacob")

I would strongly suggest to set the capacity of the slice if you have rough estimates of number of elements and ALWAYS use append to add elements to the slice. You don't have to worry about the exceeding your estimate as append WILL create new array to fit the added elements.

names := make([]string)

The above case your array has 0 capacity, and append will cause the underlying array to be created again and again. This will have impact in performance. You should avoid this. If you worry about taking up more space in the memory you might consider creating slice of pointer to a type

objList := make([]*MyStructType, 0, 100)