Skip to content

Instantly share code, notes, and snippets.

@XUJiahua
Last active March 19, 2018 07:07
Show Gist options
  • Save XUJiahua/fcc8aabbef82408b7fb272c9afa3142c to your computer and use it in GitHub Desktop.
Save XUJiahua/fcc8aabbef82408b7fb272c9afa3142c to your computer and use it in GitHub Desktop.
golang embedding of struct
package models
import "time"
type User struct {
Id int64 `json:"id"`
Name string `json:"name"`
CreatedAt time.Time `json:"created_at"`
}
type UserEmbd struct {
User
CreatedAt string `json:"created_at"`
}
package models
import (
"testing"
"time"
"encoding/json"
)
func TestUser_MarshalJSON(t *testing.T) {
u := &User{
Id:100,
Name:"john",
CreatedAt: time.Now(),
}
ue := &UserEmbd{
User: *u,
CreatedAt: "20101010",
}
t.Logf("%+v", u)
t.Logf("%+v", ue)
data, _ := json.Marshal(u)
t.Logf("%+v", string(data))
data, _ = json.Marshal(ue)
t.Logf("%+v", string(data))
}
// user_test.go:21: &{Id:100 Name:john CreatedAt:2018-03-19 15:03:38.492922 +0800 CST m=+0.100586140}
// user_test.go:22: &{User:{Id:100 Name:john CreatedAt:2018-03-19 15:03:38.492922 +0800 CST m=+0.100586140} CreatedAt:20101010}
// user_test.go:25: {"id":100,"name":"john","created_at":"2018-03-19T15:03:38.492922+08:00"}
// user_test.go:28: {"id":100,"name":"john","created_at":"20101010"}
// UserEmbd可用于接口层,User用于内部逻辑
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment