Skip to content

Instantly share code, notes, and snippets.

@mmitou
Last active November 22, 2020 17:30
Show Gist options
  • Save mmitou/8bc9f5e130c547f3c59d832da4198bdf to your computer and use it in GitHub Desktop.
Save mmitou/8bc9f5e130c547f3c59d832da4198bdf to your computer and use it in GitHub Desktop.
構造体の埋め込みの例
package main
import (
"encoding/json"
"fmt"
)
type Header struct {
ID int
Name string
}
type Foo struct {
Header
FooValue int
}
type Bar struct {
Header
BarValue string
}
func initHeader(h *Header) {
h.ID = 1234
h.Name = "hello"
}
func InitFoo(foo *Foo) {
initHeader(&foo.Header)
foo.FooValue = 100
}
func InitBar(bar *Bar) {
initHeader(&bar.Header)
bar.BarValue = "bar"
}
func main() {
foo := Foo{}
InitFoo(&foo)
fmt.Printf("foo:\n%+v\n", foo)
b, err := json.Marshal(&foo)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(b))
bar := Bar{}
InitBar(&bar)
fmt.Printf("bar:\n%+v\n", bar)
b, err = json.Marshal(&bar)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(b))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment