Variables in Go are used to store data that can be modified during the program’s execution.
Go has a unique syntax for declaring variables and offers strong typing, ensuring variables are assigned compatible data types.
Go also provides shorthand and type inference to make variable declaration more flexible.
In this tutorial, we’ll cover:
1. Declaring Variables
In Go, you declare variables using the var keyword, followed by the variable name, type, and optionally, a value. If a value is assigned, Go will infer the type of the variable.
package main import "fmt" func main() { // Declaring an integer variable with a value var age int = 30 fmt.Println("Age:", age) // Declaring a string variable with a value var name string = "Alice" fmt.Println("Name:", name) // Declaring a float variable with a value var height float64 = 5.9 fmt.Println("Height:", height) }
Output:
Age: 30 Name: Alice Height: 5.9
In this example:
- age, name, and height are declared using the var keyword, followed by their types (int, string, and float64).
- Each variable is initialized with a value.
2. Variable Types and Type Inference
If you omit the type in a var declaration, Go will infer the type based on the assigned value.
package main import "fmt" func main() { // Go infers that this is an integer var count = 10 fmt.Println("Count:", count) // Go infers that this is a string var message = "Hello, Go!" fmt.Println("Message:", message) // Go infers that this is a float64 var price = 19.99 fmt.Println("Price:", price) }
Output:
Count: 10 Message: Hello, Go! Price: 19.99
In this example:
- Go automatically infers the types of count (int), message (string), and price (float64) based on their values.
3. Multiple Variable Declarations
You can declare multiple variables in a single line by separating each variable with a comma. This can be useful for declaring related variables together.
package main import "fmt" func main() { // Declare multiple variables of the same type var x, y, z int = 1, 2, 3 fmt.Println("x:", x, "y:", y, "z:", z) // Declare multiple variables of different types var name, age, isStudent = "Bob", 25, true fmt.Println("Name:", name, "Age:", age, "Is Student:", isStudent) }
Output:
x: 1 y: 2 z: 3 Name: Bob Age: 25 Is Student: true
In this example:
- x, y, and z are declared as int variables on a single line.
- name, age, and isStudent are declared with inferred types (string, int, and bool, respectively) in one line.
4. Shorthand Variable Declarations
In Go, you can use shorthand notation (:=) to declare and initialize variables without the var keyword. This approach can only be used inside functions.
package main import "fmt" func main() { // Shorthand variable declaration message := "Hello, Go!" count := 5 price := 20.5 fmt.Println("Message:", message) fmt.Println("Count:", count) fmt.Println("Price:", price) }
Output:
Message: Hello, Go! Count: 5 Price: 20.5
In this example:
- message, count, and price are declared and initialized using shorthand notation (:=), with their types inferred based on the values.
Note: The shorthand syntax (:=) cannot be used outside a function or for redeclaring variables.
5. Zero Values in Go
In Go, variables are assigned a “zero value” if they are declared without an explicit initial value. The zero value depends on the type:
- 0 for numeric types
- false for boolean types
- “” (empty string) for string types
- nil for pointers, slices, maps, channels, and interfaces
package main import "fmt" func main() { // Variables with zero values var age int var name string var isActive bool var price float64 fmt.Println("Zero value of age:", age) fmt.Println("Zero value of name:", name) fmt.Println("Zero value of isActive:", isActive) fmt.Println("Zero value of price:", price) }
Output:
Zero value of age: 0 Zero value of name: Zero value of isActive: false Zero value of price: 0
In this example:
- age, name, isActive, and price are declared without initial values, so they receive their respective zero values.
6. Best Practices for Variables
a) Use Descriptive Names
Choose clear and descriptive names for variables to improve readability and maintainability.
var firstName = "John" var totalAmount = 100.50
b) Use Type Inference Where Appropriate
Use type inference when the type of a variable is clear from the assigned value. This makes the code cleaner and easier to read.
var isOnline = true // Go infers this as a bool message := "Hello, Go!" // Shorthand notation with type inference
c) Group Related Variables Together
Group related variables using a single var block or declare them in a single line.
var ( width = 10 height = 5 color = "red" )
d) Avoid Unused Variables
Go does not allow unused variables in a program. Unused variables will cause a compilation error. This encourages cleaner code, so make sure to remove any variables that are not used.
func main() { var unusedVar = 10 // This will cause an error if not used }
e) Be Mindful of Global Variables
Avoid excessive use of global variables, as they can lead to unexpected behaviors in large programs. Use function-scoped variables whenever possible.
var globalCount int // Use with caution func main() { localCount := 5 // Preferred scope fmt.Println("Local Count:", localCount) }
Summary
In this tutorial, we covered the basics of variables in Go:
- Declaring Variables: Using var to declare variables with or without initial values.
- Variable Types and Type Inference: Understanding typed and inferred variables.
- Multiple Variable Declarations: Declaring multiple variables of the same or different types.
- Shorthand Variable Declarations: Using := for concise declaration and initialization inside functions.
- Zero Values in Go: Understanding the default values assigned to uninitialized variables.
- Best Practices for Variables: Writing clear, maintainable, and efficient code with good variable usage practices.
By following these practices and understanding the nuances of variable declaration in Go, you can write clean, readable, and efficient code.