dony113407 2017-05-18 04:07
浏览 37
已采纳

使用位于数据存储区其他包中的(sub)struct

I haven't been able to find any information related to this.. let's say you call an API and save the resulted json into a struct in package Foo, like this:

package foo

type FooData struct {
  A string `json:"c"`
  B int    `json:"c"`
  C int64  `json:"c"`
}

Then you have your own model package:

package bar

import (
  "github.com/bla/bla/foo"
)

type BarData struct {
  A float
  Foo foo.FooData
}

Is this possible? Is there anything negative about doing it this way? The reason is the structs are over a hundred lines, so I feel it would be wasteful to duplicate it.

Also, what if I only want to index in B? Then I can just change it to:

type FooData struct {
  A string `datastore:",noindex" `json:"c"`
  B int    `json:"c"`
  C int64  `datastore:",noindex" `json:"c"`
}

?

Edit: Just to make it clear, my intention is to save the BarData struct in Datastore

  • 写回答

1条回答 默认 最新

  • doupu5941 2017-05-18 07:10
    关注

    The Go Datastore package has some documentation relating to this - https://cloud.google.com/appengine/docs/standard/go/datastore/reference#hdr-Structured_Properties

    "Structured Properties

    If the struct pointed to contains other structs, then the nested or embedded structs are flattened. For example, given these definitions:

    type Inner1 struct {
        W int32
        X string
    }
    type Inner2 struct {
        Y float64
    }
    type Inner3 struct {
        Z bool
    }
    type Outer struct {
        A int16
        I []Inner1
        J Inner2
        Inner3
    }
    

    then an Outer's properties would be equivalent to those of:

    type OuterEquivalent struct {
        A     int16
        IDotW []int32  `datastore:"I.W"`
        IDotX []string `datastore:"I.X"`
        JDotY float64  `datastore:"J.Y"`
        Z     bool
    }
    

    If Outer's embedded Inner3 field was tagged as datastore:"Foo" then the equivalent field would instead be: FooDotZ bool datastore:"Foo.Z".

    If an outer struct is tagged "noindex" then all of its implicit flattened fields are effectively "noindex"."

    So there shouldn't be any issues with you storing nested structs, just be aware that they will be flattened in datastore. It also mentions the no indexing, saying any field inherits a "noindex" from its parent struct. I don't see why your "noindex" tagging of the inner fields wouldn't work.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何解决ldsc的这条报错/index error
  • ¥15 VS2022+WDK驱动开发环境
  • ¥30 关于#java#的问题,请各位专家解答!
  • ¥30 vue+element根据数据循环生成多个table,如何实现最后一列 平均分合并
  • ¥20 pcf8563时钟芯片不启振
  • ¥20 pip2.40更新pip2.43时报错
  • ¥15 换yum源但仍然用不了httpd
  • ¥50 C# 使用DEVMOD设置打印机首选项
  • ¥15 麒麟V10 arm安装gdal
  • ¥20 OPENVPN连接问题