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

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

问题描述

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"?

推荐答案

它称为struct标记,可以使用 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.

一些使用反射的软件包,例如 json

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

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

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