GoLang Struct Tags

📢 This article was translated by gemini-3-flash-preview

Golang Series

Hello GoLang: https://blog.yexca.net/archives/154
GoLang (var and const) Variables and Constants: https://blog.yexca.net/archives/155
GoLang (func) Functions: https://blog.yexca.net/archives/156
GoLang (slice and map) Slices and Maps: https://blog.yexca.net/archives/160
GoLang (OOP) Object-Oriented Programming: https://blog.yexca.net/archives/162
GoLang (reflect) Reflection: https://blog.yexca.net/archives/204
GoLang (struct tag) Struct Tags: This Article
GoLang (goroutine) Goroutines: https://blog.yexca.net/archives/206
GoLang (channel) Channels: https://blog.yexca.net/archives/207


Struct tags allow you to describe how a field behaves when used by specific packages.

Getting Tag Values

Define tags using backticks ` (the same key used for Markdown code blocks).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package main

import (
    "fmt"
    "reflect"
)

type User struct {
    // Separate multiple tags with spaces
    name string `doc:"name" info:"nameOfUser"`
    age  int    `info:"ageOfUser"`
}

func main() {
    user := User{"zhangSan", 18}

    findTag(&user)
}

func findTag(input interface{}) {
    t := reflect.TypeOf(input).Elem()

    for i := 0; i < t.NumField(); i++ {
        tagInfo := t.Field(i).Tag.Get("info")
        tagDoc := t.Field(i).Tag.Get("doc")
        fmt.Println("info:", tagInfo, "doc:", tagDoc)
    }
}

JSON Conversion

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package main

import (
    "encoding/json"
    "fmt"
)

type User struct {
    // Fields must be exported (capitalized) to be converted to JSON
    Name string `json:"name"`
    Age  int    `json:"age"`
}

func main() {
    user := User{"zhangSan", 18}

    // struct -> json
    jsonStr, err := json.Marshal(user)
    if err != nil {
        fmt.Println("error", err)
    } else {
        fmt.Printf("jsonStr : %s\n", jsonStr)
    }

    // json -> struct
    var user2 User
    err = json.Unmarshal(jsonStr, &user2)
    if err != nil {
        fmt.Println("error", err)
    } else {
        fmt.Println(user2)
    }
}