如何在Go中初始化组合结构? [英] How do I initialize a composed struct in Go?

查看:257
本文介绍了如何在Go中初始化组合结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  type Base结构{
ID字符串
}

类型子结构{
Base $ b $ int int
b int
}

当我初始化 Child 时,我无法初始化 ID 字段。

  //未知字段'ID',类型为Child 
child:= Child {ID:id,a:a,b:b}



  child:= Child {a:23,b:42} 
child.ID =foo

这似乎违反了封装。 Child的用户必须知道ID字段有些不同。如果我后来将一个公共字段移动到嵌入式结构中,那可能会破坏初始化。



我可以写一个 NewFoo()方法,并希望每个人都使用它,但 是否有一种方法可以安全地使用结构体字面值,而嵌入式结构体不会显示某些字段被嵌入? strong>还是我在这里应用了错误的模式?

解决方案

使用嵌套复合文字初始化单个表达式中的值: / b>

  child:= Child {Base:Base {ID:id},a:a,b:b} 

无法隐藏从嵌入式结构中提升字段这一事实。


Let's say I have a struct with another struct embedded in it.

type Base struct {
    ID string
}

type Child struct {
    Base
    a int
    b int
}

When I go to initialize Child, I can't initialize the ID field directly.

// unknown field 'ID' in struct literal of type Child
child := Child{ ID: id, a: a, b: b }

I instead have to initialize the ID field separately.

child := Child{ a: 23, b: 42 }
child.ID = "foo"

This would seem to violate encapsulation. The user of Child has to know there's something different about the ID field. If I later moved a public field into an embedded struct, that might break initialization.

I could write a NewFoo() method for every struct and hope everyone uses that, but is there a way to use the struct literal safely with embedded structs that doesn't reveal some of the fields are embedded? Or am I applying the wrong pattern here?

解决方案

Use nested composite literals to initialize a value in a single expression:

child := Child{Base: Base{ID: id}, a: a, b: b}

It's not possible to hide the fact that a field is promoted from an embedded struct.

这篇关于如何在Go中初始化组合结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆