0
0
Goprogramming~5 mins

Short variable declaration in Go

Choose your learning style9 modes available
Introduction

Short variable declaration lets you quickly create and set a variable without writing its type. It makes your code shorter and easier to read.

When you want to create a new variable and assign a value in one step.
When the type of the variable can be guessed from the value you give it.
When writing simple functions or small blocks of code where brevity helps.
When you want to avoid repeating the type name to keep code clean.
Syntax
Go
variableName := value

The := symbol means 'declare and assign'.

You cannot use := to reassign an existing variable, only to declare new ones or at least one new variable in the declaration.

Examples
Creates a new variable x with the value 10. The type int is guessed automatically.
Go
x := 10
Creates a string variable called name with the value "Alice".
Go
name := "Alice"
Declares two variables pi and radius at once with their values.
Go
pi, radius := 3.14, 5
Sample Program

This program uses short variable declaration to create two variables, age and city, then prints them.

Go
package main

import "fmt"

func main() {
    age := 25
    city := "Paris"
    fmt.Println("Age:", age)
    fmt.Println("City:", city)
}
OutputSuccess
Important Notes

You must use := inside functions, not at the package level.

If you want to update an existing variable, use = instead of :=.

Summary

Short variable declaration uses := to create and assign variables quickly.

It works only inside functions and when declaring new variables.

It helps keep code clean by skipping explicit type declarations.