对 Go 中的某些数据结构语法感到困惑
Confused on certain data structure syntax in Go
过去几周我一直在学习围棋。来自 Python 和 Erlang 我喜欢这种语言,它简单而严格。然而,有一些关于结构和解析 YAML 的语法“东西”让我感到困惑。
这是我的 yml 配置。例如:
server:
host: 127.0.0.1
port: 8080
path: /some/silly/path
我看到人们声明如下结构:
Server struct {
Host string `yaml:"host"`
Path string `yaml:"path"`
Port string `yaml:"port"`
} `yaml:"server"`
}
我也看到了这个:
Server struct {
Host string `yaml:"host"`
Path string `yaml:"path"`
Port string `yaml:"port"`
}
}
在服务器结构声明的末尾添加额外的 yaml:"server" 有什么意义?
这是一个 JSON 的示例,因为它是内置的:
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)
}
如您所见,我根本没有使用任何标签。规则在这里:
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
因此,只要 JSON 键与结构字段匹配(无论大小写),那么您就不需要标签。否则你会的。通常你可以避免使用标签,除非你只是想在结构中使用不同的标签,或者如果 JSON 键有一个连字符,例如:
{"need-tag-for-this": 10}
过去几周我一直在学习围棋。来自 Python 和 Erlang 我喜欢这种语言,它简单而严格。然而,有一些关于结构和解析 YAML 的语法“东西”让我感到困惑。 这是我的 yml 配置。例如:
server:
host: 127.0.0.1
port: 8080
path: /some/silly/path
我看到人们声明如下结构:
Server struct {
Host string `yaml:"host"`
Path string `yaml:"path"`
Port string `yaml:"port"`
} `yaml:"server"`
}
我也看到了这个:
Server struct {
Host string `yaml:"host"`
Path string `yaml:"path"`
Port string `yaml:"port"`
}
}
在服务器结构声明的末尾添加额外的 yaml:"server" 有什么意义?
这是一个 JSON 的示例,因为它是内置的:
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)
}
如您所见,我根本没有使用任何标签。规则在这里:
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
因此,只要 JSON 键与结构字段匹配(无论大小写),那么您就不需要标签。否则你会的。通常你可以避免使用标签,除非你只是想在结构中使用不同的标签,或者如果 JSON 键有一个连字符,例如:
{"need-tag-for-this": 10}