结构体命名规范

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

Struct Naming Convention

问题

在给定的情况下,你可以根据个人偏好和项目需求来选择命名方式。以下是一些建议:

  1. 如果你的项目中只有一个领域(例如金融),并且不太可能扩展到其他领域,那么使用"Request"和"Response"作为结构体名称是可以接受的。

  2. 如果你的项目中可能会涉及多个领域,或者你希望更清晰地表达结构体的用途,那么可以考虑使用"FinanceRequest"和"FinanceResponse"这样的前缀命名方式。

  3. 如果你担心使用"FinanceRequest"会导致外部调用时出现重复的"finance"词汇,你可以考虑使用更具体的前缀,比如"APIRequest"和"APIResponse"。

总之,命名方式应该能够清晰地传达结构体的用途和所属领域,同时也要符合个人或团队的编码规范和偏好。

英文:

I have a few structs in a package that make a simple finance API call, one implements the request to the API, one stores the response.

I'm wondering if it's appropriate to just name the structs "Request" and "Response" respectively, or should I prefix them with the subject/package- like "FinanceRequest" and "FinanceResponse"? Or would that make external calls redundant by using finance.FinanceRequest (finance word used twice)?

Looking for thoughts on the matter (golang convention/preference)...

Samples:

package finance

type Request struct {
//...
}

type Response struct {
//...
} 

func DoSomething(r *Request) (*Response, error) {
//...
}

or

package finance

type FinanceRequest struct {
//...
}

type FinanceResponse struct {
//...
} 

func DoSomething(r *FinanceRequest) (*FinanceResponse, error) {
//...
}

答案1

得分: 8

惯例是使用Request和Response。以下是《Effective Go》对此的解释:

导入包的人将使用该名称来引用其内容,因此包中的导出名称可以利用这一事实避免重复。 (不要使用import .表示法,这可以简化必须在其测试之外运行的测试,但在其他情况下应避免使用。)例如,bufio包中的缓冲读取器类型称为Reader,而不是BufReader,因为用户将其视为bufio.Reader,这是一个清晰、简洁的名称。此外,由于导入的实体总是使用其包名进行寻址,bufio.Reader不会与io.Reader冲突。

golint工具会对名称FinanceRequest和FinanceResponse提出警告。

英文:

The convention is to use Request and Response. Here's what Effective Go has to say:

> The importer of a package will use the name to refer to its contents, so exported names in the package can use that fact to avoid stutter. (Don't use the import . notation, which can simplify tests that must run outside the package they are testing, but should otherwise be avoided.) For instance, the buffered reader type in the bufio package is called Reader, not BufReader, because users see it as bufio.Reader, which is a clear, concise name. Moreover, because imported entities are always addressed with their package name, bufio.Reader does not conflict with io.Reader.

The golint tool will complain about the names FinanceRequest and FinanceResponse.

huangapple
  • 本文由 发表于 2016年2月27日 06:07:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/35662673.html
匿名

发表评论

匿名网友

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

确定