Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any better way to handle slices of variable size?

Tags:

arrays

slice

go

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.

like image 316
castiel Avatar asked Jan 10 '23 19:01

castiel


1 Answers

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.

like image 114
RickyA Avatar answered Jan 22 '23 09:01

RickyA