Identifiers are the names given to program elements such as variables, functions, constants, packages and types. They help identify and access different parts of a Go program.
For example, in the following program, main is the package name, main() is the function name and name is the variable name.
package main
import "fmt"
func main() {
var name = "Maria"
fmt.Println(name)
}
Output
Maria
Types of Identifiers
Identifiers can be used for different program elements in a Go program, such as:
- Variable names: age, name, totalMarks
- Function names: main(), display(), calculateSum()
- Constant names: PI, MAX_SIZE, siteName
- Package names: main, fmt, math
- Type names: Student, Employee, Person
package main
import "fmt"
const siteName = "GeeksforGeeks"
type Student struct {
Name string
}
func display() {
fmt.Println(siteName)
}
func main() {
var age = 20
display()
fmt.Println(age)
}
Output
GeeksforGeeks 20
Here:
- age is a variable identifier.
- display is a function identifier.
- siteName is a constant identifier.
- main and fmt are package identifiers.
- Student is a type identifier.
Rules for Naming Identifiers
A valid Go identifier must follow these rules:
- It must start with a letter (A-Z or a-z) or an underscore (_).
- It can contain letters, digits (0-9) and underscores.
- It cannot start with a digit.
- Identifiers are case-sensitive.
- Go keywords cannot be used as identifiers.
Valid Identifiers
name
_name
user123
total_marks
Geeks
Invalid Identifiers
123name
if
for
switch
Case Sensitivity in Identifiers
Go treats uppercase and lowercase letters as different identifiers.
package main
import "fmt"
func main() {
age := 20
Age := 25
fmt.Println(age)
fmt.Println(Age)
}
Output
20 25
Explanation: Here, age and Age are two different identifiers.
Blank Identifier
The underscore (_) is known as the blank identifier. It is used when a value is required syntactically but does not need to be stored.
package main
import "fmt"
func main() {
_, b := 10, 20
fmt.Println(b)
}
Output
20
Explanation: The value 10 is assigned to _ and ignored.
Exported Identifiers
Identifiers that begin with an uppercase letter are called exported identifiers. They can be accessed from other packages.
package mathutil
var TotalMarks = 500
Since TotalMarks starts with an uppercase letter, it can be used by other packages.
Non-Exported Identifier
package mathutil
var totalMarks = 500
Since totalMarks starts with a lowercase letter, it can only be accessed within the same package.