Skip to main content

Go Variables

Variables are fundamental building blocks in any programming language. In Go, variables serve as named storage locations that hold values of specific types. Understanding how to declare, initialize, and manipulate variables is essential for writing effective Go programs.

Introduction to Variables in Go

A variable is a named memory location used to store data that can be modified during program execution. In Go, each variable has a specific type that determines what kind of data it can store and what operations can be performed on it.

Go is a statically-typed language, which means that variable types are checked at compile time. This helps catch errors early and improves program reliability.

Declaring Variables

Go provides several ways to declare variables:

1. Basic Variable Declaration

The most explicit way to declare a variable in Go is using the var keyword followed by the variable name and type:

go
var age int
var name string
var isActive bool

In this form, variables are initialized with their zero values:

  • Numeric types (int, float): 0
  • Boolean type: false
  • String type: "" (empty string)
  • Pointer, function, interface, slice, channel, map: nil

2. Variable Declaration with Initial Value

You can declare and initialize a variable in a single line:

go
var age int = 25
var name string = "Gopher"
var isActive bool = true

3. Type Inference

Go can infer the type of a variable based on the value provided:

go
var age = 25        // int
var pi = 3.14159 // float64
var name = "Gopher" // string
var isActive = true // bool

4. Short Variable Declaration

For local variables inside functions, you can use the short declaration operator (:=):

go
func main() {
age := 25
name := "Gopher"
isActive := true

// Use the variables...
}

This is the most common and concise way to declare variables in Go functions.

Example: Different Variable Declaration Methods

go
package main

import "fmt"

func main() {
// Method 1: Declaration only
var count int
count = 10

// Method 2: Declaration with initialization
var message string = "Hello, Go!"

// Method 3: Type inference
var pi = 3.14159

// Method 4: Short declaration
name := "Gopher"

// Print all variables
fmt.Println("Count:", count)
fmt.Println("Message:", message)
fmt.Println("Pi:", pi)
fmt.Println("Name:", name)
}

Output:

Count: 10
Message: Hello, Go!
Pi: 3.14159
Name: Gopher

Multiple Variable Declarations

Go allows declaring multiple variables in a single statement:

Multiple Variables of the Same Type

go
var width, height int
width, height = 100, 200

// Or combined
var width, height int = 100, 200

// Or with type inference
width, height := 100, 200

Multiple Variables of Different Types

go
var (
name string = "Gopher"
age int = 5
isActive bool = true
)

// Or with type inference
var (
name = "Gopher"
age = 5
isActive = true
)

// Or using short declaration
name, age, isActive := "Gopher", 5, true

Constants

While not variables, constants are related and important to understand:

go
const Pi = 3.14159
const (
StatusOK = 200
StatusNotFound = 404
)

Constants are declared using the const keyword and cannot be changed after declaration.

Variable Scope

The scope of a variable determines where it can be accessed in your program:

  1. Package-level variables: Declared outside any function, accessible throughout the package
  2. Local variables: Declared inside a function, accessible only within that function
  3. Block-level variables: Declared inside a block (like if, for), accessible only within that block
go
package main

import "fmt"

// Package-level variable
var globalVar = "I'm global"

func main() {
// Local variable
localVar := "I'm local to main()"
fmt.Println(globalVar) // Accessible
fmt.Println(localVar) // Accessible

if true {
// Block-level variable
blockVar := "I'm block-scoped"
fmt.Println(blockVar) // Accessible
fmt.Println(localVar) // Accessible
fmt.Println(globalVar) // Accessible
}

// fmt.Println(blockVar) // Error: blockVar is not accessible here
}

func anotherFunction() {
fmt.Println(globalVar) // Accessible
// fmt.Println(localVar) // Error: localVar is not accessible here
}

Variable Naming Rules

In Go, variable names:

  • Must begin with a letter or underscore
  • Can contain letters, digits, and underscores
  • Are case-sensitive (myVar and myvar are different variables)
  • Cannot use keywords (like if, for, func)

Go follows certain conventions:

  • Use camelCase for variable names (userName, not user_name)
  • Package-level variables with the first letter capitalized are exported (accessible from other packages)
  • Short, descriptive names are preferred

Type Conversion

Go requires explicit conversion between different types:

go
package main

import "fmt"

func main() {
var i int = 42
var f float64 = float64(i)
var u uint = uint(f)

fmt.Println(i, f, u) // 42 42 42

// String conversion
s := fmt.Sprintf("%d", i)
fmt.Println(s) // "42"
}

graph LR

A[Declare Variable] --> B[Initialize?]

B -->|Yes| C[var x Type = Value]

B -->|Yes| D[var x = Value]

B -->|Yes| E[x := Value]

B -->|No| F[var x Type]

C --> G[Use Variable]

D --> G

E --> G

F --> H[x = Value] --> G

Zero Values

Every variable declared without an explicit initial value is given its zero value:

go
package main

import "fmt"

func main() {
var i int
var f float64
var b bool
var s string
var p *int

fmt.Printf("int: %v
", i)
fmt.Printf("float64: %v
", f)
fmt.Printf("bool: %v
", b)
fmt.Printf("string: %q
", s)
fmt.Printf("pointer: %v
", p)
}

Output:

int: 0
float64: 0
bool: false
string: ""
pointer: <nil>

Real-World Examples

Example 1: Calculating Area of a Rectangle

go
package main

import "fmt"

func main() {
// Declare and initialize variables
length := 10.5 // meters
width := 5.2 // meters

// Calculate area
area := length * width

// Display result
fmt.Printf("A rectangle with length %.2f m and width %.2f m has an area of %.2f m²
",
length, width, area)
}

Output:

A rectangle with length 10.50 m and width 5.20 m has an area of 54.60 m²

Example 2: User Input and Variables

go
package main

import "fmt"

func main() {
// Declare variables
var name string
var age int

// Prompt and get user input
fmt.Print("Enter your name: ")
fmt.Scan(&name)

fmt.Print("Enter your age: ")
fmt.Scan(&age)

// Calculate birth year (approximate)
currentYear := 2023
birthYear := currentYear - age

// Display result
fmt.Printf("Hello, %s! You were born around %d.
", name, birthYear)
}

Example interaction:

Enter your name: Alice
Enter your age: 30
Hello, Alice! You were born around 1993.

Example 3: Variable Shadowing

go
package main

import "fmt"

func main() {
// Outer variable
count := 10
fmt.Println("Before if block:", count) // 10

if true {
// Inner variable shadows the outer one
count := 20
fmt.Println("Inside if block:", count) // 20
}

fmt.Println("After if block:", count) // 10
}

Output:

Before if block: 10
Inside if block: 20
After if block: 10

Common Mistakes and Best Practices

1. Unused Variables

Go will not compile if you have unused variables:

go
func main() {
x := 10 // Error: x declared and not used
}

2. Redeclaration

You cannot redeclare a variable in the same scope, but you can reassign it:

go
func main() {
x := 10
x = 20 // OK: reassignment
// x := 30 // Error: no new variables on left side of :=
}

However, you can redeclare a variable in a short declaration if at least one other variable is new:

go
func main() {
x, y := 10, 20
x, z := 30, 40 // OK: z is new
fmt.Println(x, y, z) // 30 20 40
}

3. Use Meaningful Names

Choose descriptive variable names that reflect their purpose:

go
// Poor naming
var x int = 60

// Better naming
var ageInYears int = 60

4. Keep Scope as Narrow as Possible

Declare variables close to where they're used to improve readability and reduce errors.

Summary

In this article, we covered:

  • Different ways to declare variables in Go
  • Type inference and the short declaration operator
  • Multiple variable declarations
  • Variable scoping rules
  • Naming conventions and best practices
  • Type conversion
  • Zero values
  • Real-world examples of variable usage

Understanding variables is a critical first step in learning Go programming. With this knowledge, you're ready to move on to more advanced concepts like control structures, functions, and data types.

Exercises

  1. Declare variables for a person's name, age, and height (in meters) using different declaration methods.
  2. Write a program that calculates the area and perimeter of a circle, given its radius.
  3. Create a temperature converter program that converts Celsius to Fahrenheit and vice versa.
  4. Write a program that swaps the values of two variables without using a temporary variable.
  5. Experiment with variable shadowing by creating nested blocks with variables of the same name.

Additional Resources



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)