Go 嵌入域和域的差异
有嵌入式结构Go 嵌入域和域的差异,go,struct,Go,Struct,有嵌入式结构Struct1和定义为字段的结构Struct2。两个fmt.Printf()都是相同的结果,但初始化有差异。我对此感到困惑。对不起 Struct1和Struct2之间有什么区别 在什么情况下应该使用哪个 剧本 非常感谢您的时间和建议。很抱歉我的问题不成熟。关于第二个问题,我个人主要使用嵌入来提升方法 //having type Doer interface{ Do() } func DoWith(d Doer){} func (s sample1)Do(){} //impl
Struct1
和定义为字段的结构Struct2
。两个fmt.Printf()
都是相同的结果,但初始化有差异。我对此感到困惑。对不起
Struct1
和Struct2
之间有什么区别非常感谢您的时间和建议。很抱歉我的问题不成熟。关于第二个问题,我个人主要使用嵌入来提升方法
//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
“虽然初始化有区别”——你可以用同样的方式初始化它们:
s2:=&Struct2{sample1{foo},sample2{bar}
,因为对于第一个,它们应该是指针(你这样声明):&sample1
和&sample2
。对我来说,嵌入是一种设计工具。如果一个类型通过“is a”关系与另一个类型关联,则嵌入它(但仅在必要时)。否则你不会。所以,默认情况下,我宁愿永远不要嵌入。我可以建议你去获取和阅读吗?它在以温和和渐进的方式交付材料方面具有惊人的质量,同时它处理了所有血淋淋的细节——包括嵌入。(我既不是作者也不是卖家。)这次旅行是一个很好的起点,有效围棋是一个很好的材料,但是(其中一些甚至是免费的;比如卡莱布·多克西的书)。在我读过的书中,我推荐的一本,在呈现材料的方式上是无与伦比的。唯一的问题可能是它假定有先验知识或类似C语言;完全初学者可能会迷路。谢谢你的建议和样品。这些样品对我很有帮助。我想用你的答案来解决我的问题。再次感谢你。
//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