Home > Blockchain >  What is the golang naming convention for variables/ methods starting with abbreviations
What is the golang naming convention for variables/ methods starting with abbreviations

Time:01-26

Should variables/methods in golang be named if it's starting with an abbreviation?

Is it urlToString() or URLToString()?

What is preferred here?

Naming convention in golang

CodePudding user response:

From Initialsms in the Go Code Review Comments wiki, we see:

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" (which is pretty much all cases when it's not the "id" as in "ego", "superego"), so write "appID" instead of "appId".

So the direct answer to your question:

Is it urlToString() or URLToString()?

Is "Yes."

Both are correct. Which one you use depends on whether or not your function should be exported. If it is to be exported, URLToString() is correct. If it is to be unexported, then urlToString() is correct.

As an aside: Prefer unexported, unless or until you have a compelling reason to export.

CodePudding user response:

In Go, the naming convention for variables and methods is to use CamelCase, where the first letter of the first word is lowercase and the first letter of subsequent words is uppercase. When a variable or method name starts with an abbreviation, the abbreviation should be in uppercase as well.

For example, if a variable represents a user's ID, it might be named "userID" or "UserID". Similarly, if a method retrieves a user's information, it might be named "getUserInfo" or "GetUserInfo".

Also bare in mind that Capital first letter for declared Variables, Types and functions will make them globally available, if you want just local function in a module, then lower case the first letter. Hope this helps.

CodePudding user response:

In Go known as exported and unexported for level access rights, you may use camelCase for unexported (private) modifier and use PascalCase for exported (public) level access modifier. In your case URLToString(), I prefer to use UrlToString() for exported level access

  • Related