Go Variables

Introduction to Go Variables #

Variables are one of the fundamental building blocks in any programming language, and Go is no exception.
A variable is a named storage location in your program that holds a value which can change during execution.

In Go, variables allow you to store data such as numbers, text, or more complex types, and manipulate them using the logic of your program.


✅ Why Are Variables Important? #

Variables enable programs to store and manipulate data dynamically.
Without variables, programs would not be able to perform meaningful operations beyond hardcoded behavior.

👉 Example use cases:

  • Store user input
  • Hold calculation results
  • Manage program state across multiple operations

✅ Variable Types in Go #

Go is a statically typed language, which means the type of every variable must be known at compile time.

Common data types in Go:

  • int, int8, int16, int32, int64 – For integers of different sizes
  • float32, float64 – For floating-point numbers
  • string – For text
  • bool – For boolean values (true, false)
  • Arrays, Slices, Maps – For collections of data

Example:

var count int = 10
var price float64 = 99.99
var name string = "Gopher"
var active bool = true

✅ Scope of Variables #

Variables in Go can have different scopes:

  • Local scope: Variables declared inside functions are accessible only within those functions.
  • Global scope: Variables declared outside functions are accessible throughout the package.

Example:

var globalVar int = 100  // Global variable

func main() {
    var localVar int = 50  // Local variable
    fmt.Println(globalVar)
    fmt.Println(localVar)
}

👉 Best practice: Use local variables whenever possible to avoid accidental modifications and improve code readability.


✅ Constants vs Variables #

Use const to declare values that do not change:

const Pi = 3.14

Variables are for dynamic data, whereas constants are for fixed values.


✅ Next Steps #

This section is just the beginning of understanding how variables work in Go. Explore detailed guides on:

👉 Mastering variables will help you write clean, efficient, and maintainable Go applications.