Home > Net >  golang: declaring a camelcase in a struct declaration
golang: declaring a camelcase in a struct declaration

Time:08-26

I'm trying to read a yaml file via golang.

But the "matchLabels" sub-struct is not being recognized

yaml

apiVersion: apps/v1
kind: Deployment
metadata:
    name: nginx-deploy
    labels:
      app: test
spec:
    replicas: 3
    selector:
        matchLabels:
            app: web
    

struct

type myData struct {
    Apivesion string `yaml:"apiVersion"`
    Kind      string
    Metadata  struct {
        Name   string
        Labels struct {
            App string
        }
    }
    Spec struct {
        Replicas int64
        Selector struct {
            Matchlabels struct {
                App string
            }
        }
    }
}

Expectation

&{apps/v1 Deployment {nginx-deploy {test}} {3 {{web}}}}

Result

&{apps/v1 Deployment {nginx-deploy {test}} {3 {{}}}}

Fix didn't work:

Matchlabels struct `yaml:"matchLabels"` {

CodePudding user response:

Field tags follow the type: Matchlabels struct { App string } yaml:"matchLabels" – Cerise Limón 39 mins ago

CodePudding user response:

I don't think you implemented the suggested answer correctly, see where the tag is:

type myData struct {
    Apivesion string `yaml:"apiVersion"`
    Kind      string
    Metadata  struct {
        Name   string
        Labels struct {
            App string
        }
    }
    Spec struct {
        Replicas int64
        Selector struct {
            Matchlabels struct {
                App string
            } `yaml:"matchLabels"`
        }
    }
}

See also: https://go.dev/play/p/yd9c-iBz2yL

  •  Tags:  
  • go
  • Related