DEV Community

Evan Lin
Evan Lin

Posted on • Originally published at evanlin.com on

[TIL][Golang] Golang Community FAQ (2) - Struct Tags

Preface:

I often hear some frequently asked questions in Facebook communities or the Slack channel (https://t.me/golangtw), so I decided to organize them into this article, hoping that more people can understand and get answers through searching. Since there are quite a few frequently asked questions, this is a series of compilations, and I hope to provide a more in-depth understanding by organizing them into articles.

The second article is about Struct Tags, hoping that everyone can understand more when dealing with XML and JSON data.

Related series of articles:

Struct Tags:

Excuse me, what is the syntax for putting a string directly after the struct member declaration like this?
type Person struct {
        Name string `form:"name"`
        Address string `form:"address"`
}
I can't find it in the official documentation.

Enter fullscreen mode Exit fullscreen mode

This is called struct tags Go Wiki: Well known struct tags, and it is usually used when defining JSON data formats. Here's a simple example:

package main

import "fmt"

type User struct {
    Name string `example:"name"`
}

func (u *User) String() string {
    return fmt.Sprintf("Hi! My name is %s", u.Name)
}

func main() {
    u := &User{
        Name: "Sammy",
    }

    fmt.Println(u)
}

Enter fullscreen mode Exit fullscreen mode

(Example from: How To Use Struct Tags in Go)

https://golang.org/pkg/reflect/ func (StructTag) There are some examples there.

In fact, Golang itself provides many types of Struct Tags, and JSON, XML, and bson are all relatively common formats.

https://github.com/golang/go/issues/23637

Reference:

Top comments (0)