0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

reflectパッケージで構造体情報を取得

Posted at

reflectパッケージ

GO言語におけるreflectパッケージですが、
発生遅くありません?

思いついてから実装まで一体何フレかかってんだと。
特にしばらく実装から離れていると、さらに時間がかかりますよね。

そこで、そこらへんを少しずつTipsとしてまとめていければと思ってます。

構造体の変数名とタグを取得

package main

import (
	"fmt"
	"reflect"
)

// 構造体
type Skill struct{
	p int64 `tag:"弾拳"`
	pp int64 `tag:"烈掌"`
	ppk int64 `tag:"烈空脚"`
}

// 構造体情報を出力
func do(I interface{}) {
	v := reflect.ValueOf(I)
	t := v.Type()
	for i := 0; i < t.NumField(); i++ {
		name := t.Field(i).Name
		tag := t.Field(i).Tag.Get("tag")
		fmt.Println("name="+name+" tag="+tag)
	}
}

// メイン処理
func main() {
	do(Skill{})
}

現場からは以上です。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?