Created
November 21, 2020 09:01
-
-
Save mmitou/e7f27b251ae4f5c07996c9e7f77cbcd4 to your computer and use it in GitHub Desktop.
汎用的な構造体初期化関数の例
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "fmt" | |
func main() { | |
foo := Foo{} | |
InitFoo(&foo) | |
fmt.Printf("%+v\n", foo) | |
bar := Bar{} | |
InitBar(&bar) | |
fmt.Printf("%+v\n", bar) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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