0
0
Goprogramming~5 mins

Variable declaration using var in Go

Choose your learning style9 modes available
Introduction

We use var to create a named place in the computer's memory to store data. This helps us keep and change values while the program runs.

When you want to store a number or text to use later in your program.
When you need to give a name to a value so you can use it many times.
When you want to set a variable with a specific type like int or string.
When you want to declare a variable without giving it a value right away.
When you want to change the value stored in a variable as your program runs.
Syntax
Go
var variableName type
var variableName type = value

You can declare a variable with or without an initial value.

The type tells Go what kind of data the variable will hold, like int for numbers or string for text.

Examples
Declares two variables: age as an integer and name as a string, without initial values.
Go
var age int
var name string
Declares variables with initial values: age is 30 and name is "Alice".
Go
var age int = 30
var name string = "Alice"
Declares a boolean variable isActive with the value true.
Go
var isActive bool = true
Sample Program

This program declares two variables using var. city is a string with the value "Paris". year is an integer declared first without a value, then assigned 2024. The program prints both values.

Go
package main

import "fmt"

func main() {
    var city string = "Paris"
    var year int
    year = 2024
    fmt.Println("City:", city)
    fmt.Println("Year:", year)
}
OutputSuccess
Important Notes

If you declare a variable without assigning a value, Go gives it a default value (like 0 for numbers, empty string for text).

You can assign a value later after declaring the variable.

Summary

var creates a variable with a name and type.

You can give the variable a value right away or later.

Variables store data you want to use or change in your program.