Is there any way to create a unfixed length slice in go? As a example, I want to grab all the fileNames in a directory(content/
) fill to a [] string
slice.
The content/
dir contains:
$-> tree content/
content/
├── 1.txt
├── 2.txt
└── tmp
Here is what I currently got:
package main
import (
"fmt"
"io/ioutil"
)
func listFile() []string {
list := make([]string, 100)
// as you can see, I make a slice length as 100, but that is not appropriate.
files, _ := ioutil.ReadDir("content")
i := 0
for _, f := range files{
list[i] = f.Name()
i = i+1
}
return list
}
func main(){
fmt.Print(listFile())
}
What I want to achieve is a way to simulate the behavior of ArrayList
in java, which I can just simply list.add()
and wont care about the length.
Can slice in GoLang do that?
Thanks.