嵌入式和现场的差异

艾尔莎:

有嵌入式结构Struct1Struct2定义为字段的结构两者fmt.Printf()都是相同的结果,但是初始化有所不同。我对此感到困惑。对不起。

  1. Struct1之间有什么区别Struct2
  2. 在什么情况下应该使用哪个?

脚本

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

非常感谢您的时间和建议。对于我的不成熟问题,我深表歉意。

Uvelichitel:

关于第二个问题,我个人主要使用嵌入来促进方法

//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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章