dousenjue3214 2018-09-16 20:47
浏览 48
已采纳

什么是Golang结构域命名约定?

I'm trying to learn Go, using Visual Studio Code, and I guess it's using a Go linter. I created this struct to map a JSON object into.

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

And I get these warnings...

struct field ApiEndpoint should be APIEndpoint

struct field ApiVersion should be APIVersion

I did some Googling and I can not find any requirements for struct field names regarding this. The most I've found is that if you want to make a field public you have to capitalize it.

So why is this linter warning me about these names?

I did some testing by changing Api to Abc and the linter didn't warn me to change it to "ABC". So I have to assume it's checking for names that start with "Api".

What are Go conventions for field names? Or in other words, are there other conventions I should know about?

  • 写回答

2条回答 默认 最新

  • drzk21632 2018-09-16 21:00
    关注

    For most cases the naming convention in Go is just to use camel case and start with upper case if it's a public field and lower case if it's not. But in words that are acronyms like API or URL they are written in full upper case eg. func ProxyURL(fixedURL *url.URL) on the http package.

    EDIT: I searched for a little bit more and there are guidelines for acronyms on the Go Code Review Comments. It talks about acronyms in the Initialisms section:

    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".

    So the rule for acronyms is that they should have constant case. In your case because they have to start with uppercase "A" you should write them as "API".

    Also this is just my personal opinion and I know that the code in the example might not be the exact code you are using but if it is, I think it's a bad practice to include the struct name on the field names. You are doing api.APIField but api.Field is easier to read and if you know the object is an API then there is not doubt that the Field belongs to an API.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)