Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the third parameter of a Go struct field?

Tags:

go

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

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

like image 858
BufBills Avatar asked Aug 26 '14 03:08

BufBills


People also ask

What is a Go struct?

A structure or struct in Golang is a user-defined type that allows to group/combine items of possibly different types into a single type. Any real-world entity which has some set of properties/fields can be represented as a struct.

What does * struct mean in Golang?

A struct (short for "structure") is a collection of data fields with declared data types. Golang has the ability to declare and create own data types by combining one or more types, including both built-in and user-defined types.

How do you access a field in a struct in Go?

Go struct access fields The struct fields are accessed with the dot operator. We create an empty User struct. We initialize the fields with values and read them using the dot operator.

How do you declare a struct variable in Golang?

Defining a struct typeThe type keyword introduces a new type. It is followed by the name of the type ( Person ) and the keyword struct to indicate that we're defining a struct . The struct contains a list of fields inside the curly braces. Each field has a name and a type.


1 Answers

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

From 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.

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

like image 164
OneOfOne Avatar answered Oct 07 '22 12:10

OneOfOne