简体   繁体   中英

Confused on certain data structure syntax in Go

I've been studying Go over the past few weeks. Coming from Python and Erlang I love the language, it's simplicity and strictness. However there have been some syntax "things" with respect to structs and parsing YAML that I am confused on. This is my yml config. for example:

server:
  host: 127.0.0.1
  port: 8080
  path: /some/silly/path

I see people declare structs like the following:

    Server struct {
        Host string `yaml:"host"`
        Path string `yaml:"path"`
        Port string `yaml:"port"`
        
    } `yaml:"server"`
}

And I also see this:

    Server struct {
        Host string `yaml:"host"`
        Path string `yaml:"path"`
        Port string `yaml:"port"`
    }
}

What is the point of having the additional yaml:"server" at the end of the Server struct declaration?

Here is an example with JSON, as it's built in:

package main

import (
   "encoding/json"
   "fmt"
)

func main() {
   s := `
   {
      "server": {"host": "127.0.0.1", "path": "/some/silly/path", "port": 8080}
   }
   `
   var config struct {
      Server struct {
         Host, Path string
         Port int
      }
   }
   json.Unmarshal([]byte(s), &config)
   fmt.Printf("%+v\n", config)
}

So as you notice, I didn't use any tags at all. The rule for that is here:

To unmarshal JSON into a struct, Unmarshal matches incoming object keys to the keys used by Marshal (either the struct field name or its tag), preferring an exact match but also accepting a case-insensitive match.

https://golang.org/pkg/encoding/json/#Unmarshal

So as long as the JSON key matches the struct field (regardless of case), then you don't need the tags. Otherwise you do. Usually you can avoid using tags, unless you just want to use a different tag in the struct, or if the JSON key has a hyphen, for example:

{"need-tag-for-this": 10}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM