英文:
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<- 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
}
The downside is that you will need to load/save all your properties by hand because you can't use the datastore package methods.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论