Keywords are reserved words that have predefined meanings in the Go language. They are used to define the structure and behaviour of a program, such as declaring variables, creating functions, controlling program flow and importing packages.
Since keywords are reserved by the language, they cannot be used as identifiers for variables, functions, constants or other program elements.
package main
import "fmt"
func main() {
var name = "David"
fmt.Println(name)
}
Output
David
Explanation:
- package defines the package name.
- import includes external packages in the program.
- func is used to define a function and var is used to declare a variable.
Using a Keyword as an Identifier
Keywords cannot be used as variable names or other identifiers.
package main
func main() {
var default = "Go"
}
Output
ERROR!
# command-line-arguments
/tmp/p7MPl0eEgf/main.go:4:6: syntax error: unexpected default, expected name
Explanation: default is a Go keyword, so it cannot be used as a variable name.
List of Go Keywords
Go currently has 25 keywords:
| break | case | chan | const | continue |
| default | defer | else | fallthrough | for |
| func | go | goto | if | import |
| interface | map | package | range | return |
| select | struct | switch | type | var |
Commonly Used Keywords
The following keywords are frequently used in Go programs:
| Keyword | Purpose |
|---|---|
| package | Defines the package of the program |
| import | Imports packages |
| func | Declares a function |
| var | Declares variables |
| const | Declares constants |
| if | Executes code based on a condition |
| for | Creates loops |
| switch | Selects one of multiple code blocks |
| return | Returns a value from a function |
| type | Creates custom data types |
Example: This example demonstrates how multiple Go keywords work together in a program.
package main
import "fmt"
func main() {
const language = "Go"
for i := 1; i <= 3; i++ {
if i == 2 {
fmt.Println(language)
}
}
}
Output
Go
Explanation:
- const creates a constant named language.
- for creates a loop and if checks a condition.
- fmt.Println() displays the output.
Keywords vs Identifiers
Keywords and identifiers may look similar, but they serve different purposes in a Go program. The table below highlights the main differences between them.
| Keywords | Identifiers |
|---|---|
| Reserved by the language | Created by the programmer |
| Cannot be used as names | Used to name program elements |
| Examples: if, for, func | Examples: name, age, printData |
Example: This example shows the difference between a Go keyword and an identifier.
package main
import "fmt"
func main() {
var age = 25
fmt.Println(age)
}
Output
25
Explanation: Here, var is a keyword, while age is an identifier.