I am making a basic program in Golang which outputs the number of files in your current directory and how many lines of code each file contains:
I am trying now to group the files that have the same extension and I run into problems. so, what I did is declaring a map of strings as keys and a slice of strings as value:
to store the extname as a key with its files in that slice
var m = make(map[string][]string)
I first receive in "group" function a slice of files read by the program (q argument) which looks like this:
[.gitignore README.md cmd\root.go example.go eyeball.exe go.mod go.sum main.go utils\utils.go]
Then I operate on that slice of files:
func group(q []string) {
var ext string
var checkedext []string
for _, val := range q {
ext = strings.Split(val, ".")[1]
for _, foo := range q {
secext := strings.Split(foo, ".")[1]
if ext == secext {
if !contains(checkedext, ext) {
addtogroup(ext, foo)
checkedext = append(checkedext, ext)
}
}
}
}
fmt.Println(m)
}
func contains(s []string, item string) bool {
for _, el := range s {
if el == item {
return true
}
}
return false
}
var m = make(map[string][]string)
func addtogroup(ext, file string) {
var subgroup []string
if val, ok := m[ext]; ok {
val = append(val, file)
} else {
subgroup = append(subgroup, file)
m[ext] = subgroup
}
}
and when I print the map It outputs this:
map[exe:[eyeball.exe] gitignore:[.gitignore] go:[cmd\root.go] md:[README.md] mod:[go.mod] sum:[go.sum]]
However, the above output is wrong because I have 3 .go files.
I know that range iterates through a copy of the map and I can't reference it by pointer because the map is a reference itself, I can't find a way around it, I thought of making this:
var m = make(map[string]*Data)
but I don't know If it's the best thing to do or not
I tried hard to explain what I want my program to do and what it does instead so, If I am missing any details just point me out.