Go struct 字段的第三个参数是什么? [英] What is the third parameter of a Go struct field?

查看:41
本文介绍了Go struct 字段的第三个参数是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

type Config struct {
    CommitIndex uint64 `json:"commitIndex"`
    // TODO decide what we need to store in peer struct
    Peers []*Peer `json:"peers"`
}

我明白前两列是什么,但什么是json:"commitIndex"?

I understand what the first two columns are,but what is json:"commitIndex"?

推荐答案

它被称为结构标记,可以使用 reflect 运行时包.

It's called a struct tag, they can be parsed using the reflect package at runtime.

来自https://golang.org/ref/spec#Struct_types:

一个字段声明可以跟一个可选的字符串文字标签,它成为相应字段声明中所有字段的属性.

A field declaration may be followed by an optional string literal tag, which becomes an attribute for all the fields in the corresponding field declaration.

标签通过反射接口可见,并参与结构的类型标识,否则会被忽略.

The tags are made visible through a reflection interface and take part in type identity for structs but are otherwise ignored.

一些使用反射的包,如 jsonhref="http://golang.org/pkg/encoding/xml" rel="noreferrer">xml 使用标签更好地处理特殊情况.

Some packages that use reflection like json and xml use tags to handle special cases better.

这篇关于Go struct 字段的第三个参数是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆