Skip to content

Go:StructTags

Go 언어의 struct tag 문법에 대한 설명.

About

type NvidiaSmiLog struct {
    XMLName xml.Name `xml:"nvidia_smi_log"`
    GPUs    []GPU    `xml:"gpu"`
}

위와 같이 백틱(`)으로 감싸진 부분은 Go 언어의 struct tag입니다.

Struct tag는 구조체 필드에 메타데이터를 추가하는 문법으로, 주로 직렬화/역직렬화(serialization/deserialization) 과정에서 필드 매핑을 지정할 때 사용됩니다.

읽는 방법

Go에서 struct tag는 리플렉션(reflection)을 사용하여 런타임에 읽을 수 있습니다.

package main

import (
    "fmt"
    "reflect"
)

type User struct {
    ID    int    `json:"id" db:"user_id" validate:"required"`
    Name  string `json:"name,omitempty"`
    Email string `json:"email"`
}

func main() {
    user := User{}

    // Get type information / 타입 정보 가져오기
    t := reflect.TypeOf(user)

    // Iterate through fields / 필드들을 순회
    for i := 0; i < t.NumField(); i++ {
        field := t.Field(i)

        fmt.Printf("Field: %s\n", field.Name)

        // Get entire tag string / 전체 태그 문자열 가져오기
        fmt.Printf("  Full Tag: %s\n", field.Tag)

        // Get specific tag value / 특정 태그 값 가져오기
        jsonTag := field.Tag.Get("json")
        dbTag := field.Tag.Get("db")
        validateTag := field.Tag.Get("validate")

        fmt.Printf("  json: %s\n", jsonTag)
        fmt.Printf("  db: %s\n", dbTag)
        fmt.Printf("  validate: %s\n", validateTag)
        fmt.Println()
    }
}

다음과 같이 출력됩니다:

Field: ID
  Full Tag: json:"id" db:"user_id" validate:"required"
  json: id
  db: user_id
  validate: required

Field: Name
  Full Tag: json:"name,omitempty"
  json: name,omitempty
  db: 
  validate: 

Field: Email
  Full Tag: json:"email"
  json: email
  db: 
  validate:

Lookup 메서드 사용

// Check if tag exists / 태그 존재 여부 확인
func checkTag() {
    user := User{}
    t := reflect.TypeOf(user)
    field, _ := t.FieldByName("ID")

    // Lookup returns value and boolean / Lookup은 값과 boolean을 반환
    if value, ok := field.Tag.Lookup("json"); ok {
        fmt.Printf("json tag exists: %s\n", value)
    } else {
        fmt.Println("json tag not found")
    }
}

Well-known struct tags

List of well-known struct tags

Tag

Documentation

asn1

https://pkg.go.dev/encoding/asn1

bigquery

https://pkg.go.dev/cloud.google.com/go/bigquery

bson

https://pkg.go.dev/go.mongodb.org/mongo-driver/bson

cue

https://pkg.go.dev/cuelang.org/go/cuego

datastore

https://pkg.go.dev/cloud.google.com/go/datastore

db

https://github.com/jmoiron/sqlx

dynamodbav

https://docs.aws.amazon.com/sdk-for-go/api/service/dynamodb/dynamodbattribute/#Marshal

egg

https://github.com/andrewwphillips/eggql

feature

https://github.com/nikolaydubina/go-featureprocessing

gorm

https://pkg.go.dev/github.com/jinzhu/gorm

graphql

https://github.com/samsarahq/thunder

json

https://pkg.go.dev/encoding/json

mapstructure

https://pkg.go.dev/github.com/mitchellh/mapstructure

parser

https://pkg.go.dev/github.com/alecthomas/participle

properties

https://pkg.go.dev/github.com/magiconair/properties#Properties.Decode

protobuf

https://github.com/golang/protobuf

reform

https://pkg.go.dev/gopkg.in/reform.v1

spanner

https://pkg.go.dev/cloud.google.com/go/spanner

toml

https://pkg.go.dev/github.com/pelletier/go-toml

url

https://github.com/google/go-querystring

validate

https://github.com/go-playground/validator

xml

https://pkg.go.dev/encoding/xml

yaml

https://pkg.go.dev/gopkg.in/yaml.v2

See also

Favorite site