Go Variable Naming Rules

Go Tutorial

Go (Golang) – Variable Naming Rules

Go follows strict and simple naming conventions to keep code clean, readable, and consistent. Understanding these rules is very important.


 Basic Naming Rules

  •  Must start with a letter (a–z, A–Z) or underscore (_)
  •  Can contain letters, numbers, and underscores
  •  Cannot start with a number
  •  Cannot use special characters (@, #, $, etc.)

 Valid Names

age
userName
_user
user1
totalAmount

 Invalid Names

1age // starts with number
user-name // hyphen not allowed
total$ // special character

 Case Sensitivity

Go is case-sensitive.

age // different
Age // different
  • These are treated as two different variables.

 Exported vs Unexported Variables (Very Important)

 Exported (Public)

  • Starts with a capital letter

  • Accessible outside the package

 Unexported (Private)

  • Starts with a small letter

  • Accessible only within the package


 Naming Style (Best Practices)

 Use camelCase for local variables

userAge
totalPrice

 Use PascalCase for exported variables

UserAge
TotalPrice

Avoid snake_case (not idiomatic Go)

user_age // discouraged

 Short & Meaningful Names

 Use short names for small scopes

i, j, k // loops

 Use meaningful names for clarity

studentCount
invoiceTotal

 Avoid unclear names

x1, temp2, data123

No Reserved Keywords Allowed

Go keywords cannot be used as variable names.

 Invalid

Some Go keywords:

break, case, chan, const, continue,
default, defer, else, for, func,
go, if, import, interface, map,
package, range, return, select,
struct, switch, type, var

 Use _ (Blank Identifier) Properly

The underscore _ is used to ignore values, not as a normal variable name.


Examples (Good vs Bad)

 Bad

Good


Common Naming Mistakes

  •  Using vague names (x, temp) everywhere
  •  Overly long names
  •  Using snake_case
  •  Inconsistent casing
  •  Ignoring export rules

 Best Practices for Go Variable Naming

  •  Use camelCase
  •  Start public names with capital letters
  • Keep names short but meaningful
  • Use standard Go conventions
  •  Follow consistency

 Interview Questions: Go Variable Naming

1. Are variable names case-sensitive in Go?
Yes.

2. How do you make a variable public in Go?
Start its name with a capital letter.

3. Can variable names start with _?
Yes, but rarely used.

4. Does Go allow snake_case?
Technically yes, but not recommended.

5. What naming style does Go prefer?
camelCase.


 Summary

  •  Go variable names follow strict rules
  • Case controls visibility
  •  camelCase is preferred
  • Avoid keywords and special characters
  •  Good names improve code quality

Mastering Go variable naming rules helps you write clean, idiomatic, and professional Go programs

You may also like...