Home >Backend Development >Golang >How to Access Struct Field Tags Using Go's Reflect Package?

How to Access Struct Field Tags Using Go's Reflect Package?

DDD
DDDOriginal
2024-12-16 01:02:09965browse

How to Access Struct Field Tags Using Go's Reflect Package?

Accessing Struct Field Tags via Go's Reflect Package

Reflecting on a struct's field and retrieving its tag values can be achieved using Go's reflect package. Consider the following example:

type User struct {
    name    string `json:"name-field"`
    age     int
}

// ...

user := &User{"John Doe The Fourth", 20}
getStructTag(user.name) // How to obtain the tag value here?

SOLUTION

Passing the entire struct to getStructTag is not necessary. Instead, we can utilize the reflect.TypeOf function to obtain the type of the struct and the Elem method to retrieve the underlying value type. We then employ FieldByName to access the desired struct field.

field, ok := reflect.TypeOf(user).Elem().FieldByName("name")
if !ok {
    // Handle error
}

tag := string(field.Tag)

In this case, we're utilizing Elem because user is a pointer to a struct. By accessing the FieldByName field, we can directly obtain the reflect.StructField corresponding to the "name" field. The Tag attribute of the acquired field provides access to the tag value.

DEMONSTRATION

An interactive example of this technique can be found at the following link: [Reflecting on a Struct Field's Tag](https://play.golang.org/p/_M9Q-r1fuzq).

The above is the detailed content of How to Access Struct Field Tags Using Go's Reflect Package?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn