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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With