Golang - 结构领域的首都 [英] Golang - Capitals in struct fields

查看:146
本文介绍了Golang - 结构领域的首都的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用这个库访问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)
}

在这种情况下,只有age字段更新并插入到我的数据库中。

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)

打印出:

output : &{{"Name":"xx"} 0 -1}

为什么?

推荐答案

这是因为,如果我想有一个小写的字段,只导出以大写字母开头的字段,或换句话说,在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"`
}

有关详情,请参阅文档

这篇关于Golang - 结构领域的首都的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆