GAE Go – 如何将私有变量存储在数据存储中?

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

GAE Go - How to put private variables in datastore?

问题

我正在编写一个使用Google App Engine Golang的应用程序。我想要一个具有私有变量的struct,只能通过适当的函数进行设置,例如:

type Foo struct {
    bar string
}

func (f *Foo) SetBar(b string) {
    f.bar = "BAR: "+b
}

我想要能够将这些数据存储在数据存储中。然而,看起来数据存储不会保存私有变量。

如何在数据存储中存储私有变量?

英文:

I am writing a Google App Engine Golang application. I want to have a struct with private variables that can only be set through proper functions, for example:

type Foo struct {
    bar string
}

func (f *Foo) SetBar(b string) {
    f.bar = "BAR: "+b
}

I want to be able to save this data in the datastore. However, it looks like datastore does not save private variables.

How can I store private variables in datastore?

答案1

得分: 2

你可以通过实现PropertyLoadSaver接口来实现这个功能:

func (f *Foo) Save(c chan<- datastore.Property) error {
    defer close(c)
    
    c <- datastore.Property{
        Name:  "bar",
        Value: f.bar,
    }

    return nil
}

func (f *Foo) Load(c <-chan datastore.Property) error {
    for property := range c {
        switch property.Name {
        case "bar":
            f.bar = property.Value.(string)
        }
    }
    return nil
}

不过缺点是你需要手动加载/保存所有的属性,因为你不能使用datastore包的方法。

英文:

You can if your types implement the PropertyLoadSaver interface:

func (f *Foo) Save (c chan&lt;- datastore.Property) error {
    defer close(c)
    
    c &lt;- datastore.Property {
        Name: &quot;bar&quot;,
        Value: f.bar,
    }

    return nil
}

func (f *Foo) Load(c &lt;-chan datastore.Property) error {
    for property := range c {
        switch property.Name {
        case &quot;bar&quot;:
            f.bar = property.Value.(string)
        }
    }
    return nil
}

The downside is that you will need to load/save all your properties by hand because you can't use the datastore package methods.

huangapple
  • 本文由 发表于 2014年7月11日 06:48:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/24687556.html
匿名

发表评论

匿名网友

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

确定