0
0
Goprogramming~5 mins

Why variables are needed in Go

Choose your learning style9 modes available
Introduction

Variables let us store and reuse information in a program. They help keep data organized and easy to change.

When you want to remember a user's name to greet them later.
When you need to keep track of a score in a game.
When you want to store a number that changes, like a counter.
When you want to hold input from a user to use it in calculations.
When you want to save results from a calculation to use again.
Syntax
Go
var variableName type = value

// or using shorthand inside functions
variableName := value

Use var to declare a variable with a type and optional initial value.

Inside functions, you can use := to declare and assign a variable quickly.

Examples
Declare an integer variable named age and set it to 30.
Go
var age int = 30
Declare a string variable name and assign "Alice" using shorthand.
Go
name := "Alice"
Declare a boolean variable isActive without setting a value (defaults to false).
Go
var isActive bool
Sample Program

This program shows how to create variables to store a player's name and score. It prints them, then changes the score and prints it again.

Go
package main

import "fmt"

func main() {
    var score int = 10
    playerName := "Bob"
    fmt.Println("Player:", playerName)
    fmt.Println("Score:", score)

    // Update score
    score = 20
    fmt.Println("Updated Score:", score)
}
OutputSuccess
Important Notes

Variables make your code flexible by letting you change values without rewriting the whole program.

Always give variables clear names so your code is easy to understand.

Summary

Variables store information to use later in your program.

They help keep data organized and easy to update.

Use var or shorthand := to create variables in Go.