在Go,CamelCase或Semi-CamelCase中以哪种方式命名函数? [英] Which way to name a function in Go, CamelCase or Semi-CamelCase?

查看:115
本文介绍了在Go,CamelCase或Semi-CamelCase中以哪种方式命名函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Go中编写一个函数,以将文档插入MongoDB数据库的集合中.

I want to write a function in Go to insert a document into a collection in a MongoDB database. Which way to name the function is better,

  • writeToMongoDB
  • WriteToMongoD?
  • writeToMongoDB or
  • WriteToMongoD?

第二个是CamelCase,虽然我看到有人使用第一个的样式,所以我不确定哪个更合适.谢谢.

The second is CamelCase, while I saw someone using the style of the first one, so I am not sure which one is more appropriate. Thanks.

推荐答案

语法

在Go中,这不是样式问题,而是语法问题.

Syntax

In Go this is not a matter of style, it is a matter of syntax.

导出的名称(即,可以从除定义它们的包以外的其他程序包中使用的标识符)以大写字母开头.因此,如果您的方法是公共API的一部分,则应将其编写为:

Exported names (that is, identifiers that can be used from a package other than the one where they are defined) begin with a capital letter. Thus if your method is part of your public API, it should be written:

WriteToDB

但是,如果它是内部帮助器方法,则应编写为:

but if it is an internal helper method it should be written:

writeToDB

与使用关键字定义导出性(externpublic等)相比,以这种方式进行操作的好处在于,使其成为名称的一部分可以确保使用标识符的任何地方都可以分辨出是否是否导出而不必查找定义的位置(以查看定义是否包含关键字).

The benefit of doing it this way over using keywords to define exportedness (extern, public, etc.) is that making it a part of the name ensures that anywhere an identifier is used you can tell if it is exported or not without having to find where it was defined (to see if the definition contains a keyword).

另请参见:规范中的 导出的标识符 .

See also: Exported Identifiers from the spec.

因为Go是UTF-8编码的,并且支持标识符名称中具有letter或numers属性的任何Unicode字符,某些不区分大小写的语言环境的人可能无法创建导出的方法(默认为不导出) ).在这种情况下(双关语是故意的),通常在标识符前加上X前缀以指示导出.例如:X日本語

Because Go is UTF-8 encoded and supports any Unicode character with the letters or numers property in identifier names some people in locales that don't have a concept of case may have trouble creating exported methods (the default is non-exported). In this case (pun intended) it is common to prefix identifiers with an X to indicate exportedness. For example: X日本語

另请参见: Unicode标识符有什么作用? 通过常见问题解答.

See also: What's up with Unicode identifiers? from the FAQ.

就一般样式而言,应始终使用驼峰式大小写(如前所述,首字母除外).这包括常量,函数和其他标识符.因此,例如(导出的)常量列表可能看起来像:

As far as the general style goes, it is to always use camel-case (except for the first letter, as previously mentioned). This includes constants, functions, and other identifiers. So for example a list of (exported) constants might look like:

const (
    StateConnected = iota
    StateError
    StateDone

    internalStateMask = 0x2 
)

此外,缩写词总是用相同的大小写来书写,因此您可以编写以下内容之一:

Furthermore, abbreviations are always written with the same case, so you would write one of the following:

dbWrite
writeDB

而不是writeDbDbWrite.

这篇关于在Go,CamelCase或Semi-CamelCase中以哪种方式命名函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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