嵌入式结构Struct1
和结构Struct2
定义为字段。两个fmt.Printf()
都是相同的结果,而初始化有所不同。我对此感到困惑。对不起。
Struct1
和Struct2
之间有什么不同?type sample1 struct {
Data string
}
type sample2 struct {
Data string
}
type Struct1 struct {
*sample1
*sample2
}
type Struct2 struct {
Sample1 sample1
Sample2 sample2
}
func main() {
s1 := &Struct1{
&sample1{},
&sample2{},
}
s1.sample1.Data = "s1 sample1 data"
s1.sample2.Data = "s1 sample2 data"
s2 := &Struct2{}
s2.Sample1.Data = "s2 sample1 data"
s2.Sample2.Data = "s2 sample2 data"
fmt.Printf("%s, %s\n", s1.sample1.Data, s1.sample2.Data)
fmt.Printf("%s, %s\n", s2.Sample1.Data, s2.Sample2.Data)
}
https://play.golang.org/p/gUy6gwVJDP
非常感谢你的时间和建议。我很抱歉我的问题不成熟。
答案 0 :(得分:1)
关于第二个问题,我个人主要使用嵌入来推广方法
//having
type Doer interface{
Do()
}
func DoWith(d Doer){}
func (s sample1)Do(){} //implemented
type Struct1 struct {
sample1
}
type Struct2 struct {
Sample1 sample1
}
var s1 Struct1
var s2 Struct2
//you can call
DoWith(s1) //method promoted so interface satisfied
//but cannot
DoWith(s2)
并解码JSON,
//having
type Sample1 struct {
Data string `json:"data"`
}
type Sample2 struct {
Number int `json:"number"`
}
//you can easy and handy compose
type Struct1 struct {
Sample1
Sample2
}
var s1 Struct1
json.Unmarshal([]byte(`{"data": "foo", "number": 5}`), &s1)
fmt.Println(s1.Data, s1.Number) //print foo 5