Skip to content

Instantly share code, notes, and snippets.

@mmitou
Created November 21, 2020 09:01
Show Gist options
  • Save mmitou/e7f27b251ae4f5c07996c9e7f77cbcd4 to your computer and use it in GitHub Desktop.
Save mmitou/e7f27b251ae4f5c07996c9e7f77cbcd4 to your computer and use it in GitHub Desktop.
汎用的な構造体初期化関数の例
package main
import "fmt"
func main() {
foo := Foo{}
InitFoo(&foo)
fmt.Printf("%+v\n", foo)
bar := Bar{}
InitBar(&bar)
fmt.Printf("%+v\n", bar)
}
package main
import (
"reflect"
)
type Foo struct {
ID int
Name string
FooValue int
}
type Bar struct {
ID int
Name string
BarValue string
}
func initCommonFields(obj interface{}) {
v := reflect.ValueOf(obj).Elem()
v.FieldByName("ID").SetInt(1234)
v.FieldByName("Name").SetString("abc")
}
func InitFoo(foo *Foo) {
initCommonFields(foo)
foo.FooValue = 100
}
func InitBar(bar *Bar) {
initCommonFields(bar)
bar.BarValue = "bar"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment