Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which way to name a function in Go, CamelCase or Semi-CamelCase?

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 or
  • WriteToMongoD?

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.

like image 236
Tim Avatar asked Jul 27 '16 15:07

Tim


People also ask

Does go use camelCase?

The convention in Go is to use MixedCaps or mixedCaps (simply camelCase) rather than underscores to write multi-word names. If an identifier needs to be visible outside the package, its first character should be uppercase.

Should functions be camelCase?

According to PSR-1, class names should be in PascalCase, class constants should be in MACRO_CASE, and function and method names should be in camelCase.


Video Answer


1 Answers

Syntax

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

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

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.

i18n

Because Go is UTF-8 encoded and supports any Unicode character with the letters or numbers 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日本語

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

Style

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 

instead of writeDb or DbWrite.

like image 67
Sam Whited Avatar answered Oct 04 '22 20:10

Sam Whited