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.
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.
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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With