GAE Go datastore – 忽略某些变量?

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

GAE Go datastore - ignoring some variables?

问题

假设我开始将这个结构保存到数据存储中:

type Foo struct {
    Important string
    NotImportant string
}

但后来我决定我不再关心 NotImportant,并且希望停止支持它。问题是,我的数据存储已经填充了数据,我不能只是删除它并用更新后的结构替换整个数据库。我知道可以创建自定义的 Load 和 Save 方法,例如 Load(c <-chan datastore.Property) error {,但这需要在一个大的结构上付出很多努力。

有没有一种简单的方法告诉 Google App Engine Go 数据存储在保存时忽略某些变量,并且不会抱怨我加载数据的结构不再具有我不再关心的变量?

英文:

Say I start by saving this structure into datastore:

type Foo struct {
    Important string
    NotImportant string
}

But later I decide that I don't really care for NotImportant anymore and would like to stop supporting it. The problem is, my datastore is already populated with data and I can't just drop it and replace the entire database with an updated structure. I know it is possible to create custom Load and Save methods like Load(c &lt;-chan datastore.Property) error {, but that would require a lot of effort on a large struct.

Is there some easy way to tell Google App Engine Go datastore to ignore some variable when saving and not complain that the structure I'm loading the data into doesn't have the variable I don't care about any more?

答案1

得分: 7

你可以这样做:

if err != nil && err != err.(*datastore.ErrFieldMismatch) {			
}
英文:

You could do that

if err != nil &amp;&amp; err != err.(*datastore.ErrFieldMismatch) {			
}

答案2

得分: 3

请看这里:https://cloud.google.com/appengine/docs/go/datastore/reference
特别是关于属性的部分。

type Foo struct {
    Important string
    NotImportant string `datastore:"-"` 
}

这个 datastore:"-" 部分被称为结构标签。它们允许您指定有关结构字段的元数据。"-" 表示忽略此字段。Go规范在这里讨论了它们:https://golang.org/ref/spec#Struct_types

encoding/json包(以及许多其他包)也有类似的标签。

英文:

See here: https://cloud.google.com/appengine/docs/go/datastore/reference
Specifically the section on Properties.

type Foo struct {
    Important string
    NotImportant string `datastore:&quot;-&quot;`
}

That datastore:&quot;-&quot; bit is called a struct tag. They allow you to specify metadata about struct fields. A "-" means ignore this field. The Go spec discusses them here: https://golang.org/ref/spec#Struct_types

The encoding/json package (and many others) have similar tags.

huangapple
  • 本文由 发表于 2015年2月28日 10:55:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/28777595.html
匿名

发表评论

匿名网友

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

确定