go - 什么是 Golang 结构字段命名约定?

标签 go

我正在尝试使用 Visual Studio Code 学习 Go,我猜它正在使用 Go linter。我创建了这个结构来将 JSON 对象映射到。

type someAPI struct {
    ApiEndpoint string   `json:"apiEndpoint"`
    ApiVersion  string   `json:"apiVersion"`
    ...
}

我收到这些警告...

struct field ApiEndpoint should be APIEndpoint

struct field ApiVersion should be APIVersion

我做了一些谷歌搜索,但找不到与此相关的结构字段名称的任何要求。我发现的最多的是,如果您想公开一个字段,则必须将其大写。

那么为什么这个 linter 会警告我这些名字?

我通过将 Api 更改为 Abc 进行了一些测试,并且 linter 没有警告我将其更改为“ABC”。所以我必须假设它正在检查以“Api”开头的名称。

字段名称的 Go 约定是什么?或者换句话说,还有其他我应该了解的约定吗?

最佳答案

对于大多数情况,Go 中的命名约定只是使用驼峰式大小写,如果是公共(public)字段则以大写开头,否则以小写开头。但是在像 API 或 URL 这样的首字母缩略词中,它们是用完整的大写字母写的,例如。 func ProxyURL(fixedURL *url.URL)http package 上.

编辑: 我搜索了更多,在 Go Code Review Comments 上有首字母缩略词指南。 .它讨论了 Initialisms 中的首字母缩略词部分:

Words in names that are initialisms or acronyms (e.g. "URL" or "NATO") have a consistent case. For example, "URL" should appear as "URL" or "url" (as in "urlPony", or "URLPony"), never as "Url". As an example: ServeHTTP not ServeHttp. For identifiers with multiple initialized "words", use for example "xmlHTTPRequest" or "XMLHTTPRequest".

This rule also applies to "ID" when it is short for "identifier", so write "appID" instead of "appId".

所以首字母缩略词的规则是它们应该有固定的大小写。在您的情况下,因为它们必须以大写字母“A”开头,所以您应该将它们写为“API”。

此外,这只是我的个人意见,我知道示例中的代码可能与您使用的代码不完全相同,但如果是,我认为在字段名称中包含结构名称是一种不好的做法。您正在执行 api.APIFieldapi.Field 更易于阅读,如果您知道该对象是一个 API,那么毫无疑问该字段属于一个 API。

关于go - 什么是 Golang 结构字段命名约定?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52358247/

相关文章:

go - 为什么 strings.Builder 在我的测试程序中追加字符串比 fmt.Sprint 慢?

string - Golang 中的 *string 和 string 有什么区别?

connection - 读取直到服务器关闭连接

for-loop - 我如何在 Golang 中跳出无限循环

c - 使用 Go 1.5 buildmode=c-archive 和从 C 链接的 net/http.Server

go - 何时使用 os.Exit() 和 panic()?

Golang 运算符重载

data-structures - Golang - 结构之间的转换

macos - RabbitMQ Go 教程日志.Printf 无法写入磁盘文件?

go - 在go项目中打包tor