首頁  >  文章  >  後端開發  >  ## 為什麼我無法使用巢狀切片從 Go 資料儲存中檢索實體?

## 為什麼我無法使用巢狀切片從 Go 資料儲存中檢索實體?

Barbara Streisand
Barbara Streisand原創
2024-10-27 10:06:30563瀏覽

## Why Can't I Retrieve Entities from Go Datastore with Nested Slices?

Go 資料儲存錯誤:嵌套結構切片

為了利用Go 來增強效能,您在嘗試時遇到錯誤從Python 中定義的AppEngine 資料儲存區檢索實體。錯誤訊息「資料儲存:扁平化嵌套結構導致切片切片:欄位「訊息」」表示 Go 和 Python 專案模型之間的結構不符。

Go 模型定義與資料儲存相容性

Go 資料儲存包對於資料模型的結構有一定的限制。它不支援切片內的嵌套切片,例如 ModelA 定義中的“Messages”欄位。這意味著雖然您可以在 ModelA 中擁有 ModelB 實體的切片,但 ModelB 本身在自己的欄位中不能擁有任何切片。

解決錯誤的替代選項

要解決此錯誤,您有多種選擇:

  1. 避免使用Go 進行資料儲存互動:放棄使用Go 進行資料儲存互動並繼續使用Python。
  2. 自訂反序列化器:開發您自己的自訂資料儲存反序列化器,可以處理切片的巢狀切片。然而,這種方法很複雜,可能需要付出巨大的努力。
  3. 重新定義資料結構:修改您的 Python 資料結構以符合 Go 的限制。這涉及從 ModelA 或 ModelB 中刪除嵌套切片並相應地重組資料。

範例:用於自訂反序列化的PropertyLoaderSaver

如果您選擇自訂反序列化器方法,您可以為ModelA 定義一個PropertyLoaderSaver介面實作來處理「Messages」欄位的反序列化。這是一個範例:

<code class="go">import (
    "appengine_internal/datastore"
    "code.google.com/p/goprotobuf/proto"

    pb "appengine_internal/datastore"
)

type ModelA struct {
    DateJoin          time.Time `datastore:"date_join,"`
    Name              string    `datastore:"name,"`
    OwnerSalutation   string    `datastore:"owner_salutation,noindex"`
    OwnerEmailAddress string    `datastore:"owner_email_address,"`
    LogoURL           string    `datastore:"logo_url,noindex"`
    Messages          []ModelB  `datastore:"-"`
}

// Load implements the PropertyLoaderSaver interface.
func (seller *ModelA) Load(c <-chan datastore.Property) error {
    f := make(chan datastore.Property, 100)
    for p := range c {
        if p.Name == "bm" {
            var val pb.EntityProto
            err := proto.Unmarshal([]byte(p.Value.(string)), &amp;val)
            if err != nil {
                return err
            }
            // TODO: Store the result as a new ModelB instance.
        } else {
            f <- p
        }
    }
    close(f)
    return datastore.LoadStruct(seller, f)
}</code>

以上是## 為什麼我無法使用巢狀切片從 Go 資料儲存中檢索實體?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn