如何在Go中将一个结构体存储在另一个结构体中?

huangapple go评论85阅读模式
英文:

How to store a struct inside a struct in go?

问题

我有两个结构体(NewDailyPrediction),其中DailyPrediction结构体是New结构体的一个实体:

type New struct {
    Id string
    DailyPrediction
}

type DailyPrediction struct {
    Prediction string
}

我无法在数据存储中读取(或写入)New结构体。如果有人能帮助我解决这个问题,将会非常有帮助。

英文:

I have two structure (New and DailyPrediction) with DailyPrediction structure as one of the entity of New structure:

type New struct {
    Id string
    DailyPrediction
}

type DailyPrediction struct {
    Prediction string
}

I am unable to read (or) write the structure new in the datastore. It would be helpful if someone can help me on this.

答案1

得分: 1

从你的问题中,我无法清楚地了解你在使用结构体时具体在做什么,以及它以何种方式失败。然而,尽管你通过不给它命名将DailyPrediction结构体嵌入到你的新结构体中,但它仍然需要初始化。你可以在这里看到如何进行初始化的详细信息:
http://golang.org/doc/effective_go.html#embedding

例如,为了初始化你的New结构体,你可以使用类似这样的代码:

    n := New{"foo", DailyPrediction{"bar"}}

这可能是你所缺少的内容。

英文:

It is unclear to me from your question what exactly you are doing with the struct, and in what way it is failing. However, while you are embedding the DailyPrediction struct in your new struct by not giving it a name, it still needs to be initialized. You can see details of how to do that here:
http://golang.org/doc/effective_go.html#embedding

For example, in order to initialize your New struct, you may use a line like this:

    n := New{"foo", DailyPrediction{"bar"}}

Could that be what was missing?

答案2

得分: 1

不被appengine支持

英文:

Not supported by the appengine.

答案3

得分: 0

只是为了更新这篇文章给未来的读者……这个信息已经过时了……现在支持嵌套结构体。

英文:

Just to update this post for future readers ... this info is OLD ... nested structs are now supported

huangapple
  • 本文由 发表于 2012年12月7日 17:32:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/13760331.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定