Q:

Unable to map and unmarshal yaml array to golang struct

I want to unmarshal my ~/.kube/config file into a go struct.
I am using the following approach
func ListContexts(pathToKubeConfig string) ([]string, error) {
    type Contexts struct {
        Ctx []string `yaml:"contexts"`
        //ApiVersion string              `yaml:"apiVersion"`
    }
    var ctx []string
    var c Contexts

    file, err := ioutil.ReadFile(pathToKubeConfig)
    if err != nil {
        return nil, err
    }

    err = yaml.Unmarshal(file, &c)
    fmt.Printf("%#v\n", c.Ctx)
    return ctx, nil
}
}

As is widely known, a kubeconfig file has the following struct:
apiVersion: v1
. . . 
contexts:
- context:
    cluster: cluster1
    user: user1
  name: context1
- context:
    cluster: cluster2
    user: user2
  name: context2

My approach is printing:
[]string(nil)

Since context is a yaml array, why my mapping into a string array not working?
When I uncomment the ApiVersion field of my struct and try to print it, it works.

A:

context is an array, but not a string array. Either use []map[string]interface{} for context, or define the context as a struct, and use its array:
type context struct {
   Cluster string `yaml:"cluster"`
   ...
}

type contexts struct {
   Contexts []context `yaml:"contexts"`
}

