英文:
create struct containing fields of another struct
问题
如何创建一个包含另一个结构体字段的结构体?
type box struct {
x int
y int
}
type textbox struct {
box // 包含box结构体的字段
text string
}
在上述代码中,我们定义了两个结构体:box和textbox。textbox结构体包含了一个名为box的字段,该字段的类型是box结构体。这样,textbox结构体就可以访问和使用box结构体中定义的字段和方法。另外,textbox结构体还有一个名为text的字符串类型字段。
希望这个回答对你有帮助!如果你还有其他问题,请随时提问。
英文:
How can I make a struct with fields of another struct
struct box {
x int
y int
}
struct textbox {
BOXVALUES
text string
}
答案1
得分: 5
Go语言没有像Java那样的继承概念,你不能说textbox是box的子类,从而继承它的字段。
在Go中,你可以这样做:
type box struct {
x int
y int
}
type textbox struct {
box
text string
}
通过在textbox结构体中指定box类型而不带有结构体字段名,你可以将box结构体中定义的字段复制到textbox结构体中。然而,在构造过程中,你仍然需要显式地初始化box的字段,例如:
t := textbox {
box: box{
x: 1,
y: 2,
},
text: "aoeu",
}
然而,你不再需要在textbox内部引用box来访问它,例如:
println(t.x)
Go在这方面有点奇怪,因为struct不是一个对象,所以textbox实际上并不继承自box,而是将其复制到自己内部,并提供了一些语法糖来进行访问。
英文:
Go doesn't have the concept of inheritance like say Java, where you can say that textbox is a child of box and thus inherits its fields.
So you can do this:
type box struct {
x int
y int
}
type textbox struct {
box
text string
}
By specifying type box without a struct field name you copy the fields defined in the box struct int textbox. However during construction you still have to explicitly initialise box fields as:
t := textbox {
box: box{
x: 1,
y: 2,
},
text: "aoeu",
}
However you no longer need to reference box within textbox for access, for example:
println(t.x)
Go is a little weird in that regards, as struct isnt an object so textbox doesnt actually inherit from box, but rather have it copied into it whith some syntactical sugar for access.
答案2
得分: 1
我们有至少两种方式:
情况1:称为Embed
结构体textbox {
box
text string
}
情况2:包含子结构体
结构体textbox {
boxValue box
text string
}
但是我认为你应该学习基础课程。这是一个基本概念。
英文:
We have least 2 way:
case 1: called Embed
struct textbox {
box
text string
}
case 2: include child struct
struct textbox {
boxValue box
text string
}
But I think you should learn basic lesson. This is a basic concept.
答案3
得分: -2
不熟悉GO语言...但根据你给出的语法,看起来你想要的是:
type textbox struct {
box BOXVALUES
text string
}
根据你目前给出的语法,结构体应该由以下形式组成:
字段名 数据类型
在你的示例中,对于Textbox,你缺少了数据类型,比如int、string、float等。你的box结构体基本上是一个新的数据类型,所以你可以在需要数据类型的地方使用它。
英文:
Not familiar with GO...but given the syntax it looks like you want
struct textbox
{
BOXVALUES box
text string
}
According to the syntax you gave which is all have to go on at the moment the struct should consist of a
fieldname DataType
In your example for the Textbox you are missing the DataType...like int, string, float, etc. Your box struct is basically a new DataType so you can use it in place of where you would a DataType.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论