Appending to slice in map which is type of map[any]any

167 views Asked by At

I want to append to slice in map which is defined as map[any]any

I am having type conversion issues and don't know how to treat result[index][ABSPath] as slice so I can append data to it

Here is the example code:

package main

import (
    "fmt"
    "io/fs"
    "os"
    "strings"
)

func contains(target []map[any]any, key string) (int, bool) {

    for index, entry := range target {
        if _, exists := entry[key]; exists {
            return index, true
        }
    }
    return -1, false
}

func getPath(path string, filename string) string {
    return path[0:strings.Index(path, filename)]
}

func main() {

    path := os.Args[1]
    handle := os.DirFS(path)
    result := make([]map[any]any, 0)

    _ = fs.WalkDir(handle, ".", func(path string, d fs.DirEntry, err error) error {
        ABSPath := getPath(path, d.Name())
        if index, exists := contains(result, ABSPath); exists {
                        // this line fails
            result[index][ABSPath] = append(result[index][ABSPath], d.Name())
        } else {
        
            result = append(result, map[any]any{ABSPath: []string{d.Name()}})
        }
        return nil
    })

    fmt.Println(result)
}

I am new in golang and not sure how to solve this problem. This is the error I am getting: # learning/test/1 ./main.go:43:36: first argument to append must be a slice; have result[index][ABSPath] (map index expression of type any)

Note: I already tested and know that making result := make([]map[string][]string, 0) will solve the issue, however for learning purposes, I want to do it with "any".

ANSWER for others having similar problem: I have solved this issue by doing slice conversion as below:

result[index][ABSPath] = append(result[index][ABSPath].([]string), d.Name())
0

There are 0 answers