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 为什么shp文件会有这种小方块?
  • ¥15 ecplise在连接数据库时显示加载驱动成功但是数据库连接失败
  • ¥15 visionmaster启动失败,提示为“机器不满足授权而被禁用”
  • ¥15 IDEA中圈复杂度如何具体设置
  • ¥50 labview采集不了数据
  • ¥15 Multisim红外倒车雷达仿真中距离问题
  • ¥15 请上面代码做什么处理或什么混淆
  • ¥15 英雄联盟自定义房间置顶
  • ¥15 W5500网线插上无反应
  • ¥15 如何用字典的Key,显示在WPF的xaml中