结构领域的资本 [英] Capitals in struct fields
问题描述
我正在使用该库来访问CouchDB(具体来说为cloudant)"github.com/mikebell-org/go-couchdb",但我注意到了一个问题.
I'm using this library to access CouchDB (cloudant to be specific) "github.com/mikebell-org/go-couchdb" and I've noticed a problem.
当我将文件添加到数据库并传递结构时,仅添加以大写字母开头的结构字段.
When I go to add a file to the database and pass in a struct, only the fields of the struct which started with a capital letter get added.
例如
type Person struct {
name string
Age int
}
func main() {
db, _ := couchdb.Database(host, database, username, password)
joe := Person{
name: "mike",
Age: 190,
}
m, _ := db.PostDocument(joe)
}
在这种情况下,只有年龄"字段被更新并插入到我的数据库中.
In this case, only the "age" field got updated and inserted into my database.
在另一种情况下,我也注意到了这个问题-当我这样做时:
I've noticed this problem in another case also - when I'm doing something like this :
type Sample struct {
Name string
age int
}
joe := Sample{
Name: "xx",
age: 23,
}
byt, _ := json.Marshal(joe)
post_data := strings.NewReader(string(byt))
fmt.Println(post_data)
在这种情况下,只有名称会被打印出来:
in this case, only Name would be printed out :
output : &{{"Name":"xx"} 0 -1}
这是为什么?并且如果我想使用一个小写的字段并将其放入数据库中,那有可能吗?
Why is this? and If I would like to have a field with a lowercase and be inside the database, is that possible?
推荐答案
这是因为仅导出以大写字母开头的字段,或者换句话说,在curent程序包之外(在这种情况下,在json
程序包中) ).
This is because only fields starting with a capital letter are exported, or in other words visible outside the curent package (and in the json
package in this case).
以下是与此相关的规范的一部分: http://golang.org/ref/spec#Exported_identifiers
Here is the part of the specifications refering to this: http://golang.org/ref/spec#Exported_identifiers
不过,您可以使用所谓的标签"来解组不以大写字母开头的json字段.对于json
包,这是要使用的语法:
Still, you can unmarshall json fields that do no start with a capital letters using what is called "tags". With the json
package, this is the syntax to use:
type Sample struct {
Name string `json:"name"`
Age int `json:"age"`
}
有关此信息,请参见文档.
这篇关于结构领域的资本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!