Go Variable Naming Rules

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.


1️⃣ 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

2️⃣ Case Sensitivity

Go is case-sensitive.

age // different
Age // different

👉 These are treated as two different variables.


3️⃣ Exported vs Unexported Variables (Very Important)

🔹 Exported (Public)

  • Starts with a capital letter

  • Accessible outside the package

var UserName string
var TotalMarks int

🔹 Unexported (Private)

  • Starts with a small letter

  • Accessible only within the package

var userName string
var totalMarks int

4️⃣ 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

5️⃣ 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

6️⃣ No Reserved Keywords Allowed

Go keywords cannot be used as variable names.

❌ Invalid

var func int
var package string

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

7️⃣ Use _ (Blank Identifier) Properly

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

_, err := strconv.Atoi("123")

8️⃣ Examples (Good vs Bad)

❌ Bad

var A int
var x123 int
var total_amount int

✅ Good

var age int
var userID int
var totalAmount int

Summary

✔ Start with letter or _
✔ Case-sensitive
✔ Capital letter = public
✔ Small letter = private
✔ Avoid special characters & keywords
✔ Use camelCase / PascalCase

You may also like...