reflect.New().Interface()をNonPointerなstructに変換する
reflect.New()を使うとドキュメントにもある通りPointerの値が返ってくる
New returns a Value representing a pointer to a new zero value for the specified type. That is, the returned Value’s Type is PtrTo(typ).
ただし、pointerではない元の情報を取得したいときがある
そんな時はこんな感じで取得できる
v := reflect.New(t).Interface()
if t.Kind() != reflect.Ptr {
v = reflect.ValueOf(v).Elem().Interface()
}
サンプルコード
https://gist.github.com/Konboi/e88ea92960a4c4c1cd5db18cc017ac02
※ reflect.New()
に渡るt
が既にPointerの場合 reflect.New(t).Interface()
ではPointerのPointerが返ってくるので注意が必要
おまけ
reflectに関してはみんなのGoの第5章がとても参考になった