ぶろぐ

日記です

Go reflectを使ってstructの値全てに処理を行う


例えばstructのfieldに `null` という文字が含まれていたら空文字に変換する処理

package main

import (
	"fmt"
	"reflect"
)

func main() {
	h := Hoge{
		Foo:     "null",
		Bar:     "aaa",
		Integer: 2,
	}
	fmt.Println("before:", h)
	ReplaceNullStringToEmpty(&h)
	fmt.Println("after :", h)
}

type Hoge struct {
	Foo     string
	Bar     string
	Integer int64
}

func ReplaceNullStringToEmpty(s interface{}) {
	val := reflect.ValueOf(s).Elem()

	for i := 0; i < val.NumField(); i++ {
		if val.Field(i).Kind() == reflect.String {
			if val.Field(i).String() == "null" {
				val.Field(i).SetString("")
			}
		}
	}
}
go run main.go
before: {null aaa 2}
after : { aaa 2}