Variables in Go are declared using the var keyword:
var age int
var name string = "Alice"
var ready = true // inferred typeInside functions, you can use := to declare and initialize a variable in one step:
This is the most common way to create variables inside a function body.
You can group variable declarations for cleaner code:
var (
title string
price float64
inStock bool
)Use const for fixed values that cannot change:
const Pi = 3.14159
const Greeting = "Welcome"Constants must be assigned at compile time, not via function calls.
Variables declared outside functions have package scope. Inside functions, they are local. Variables in shorter blocks (like if or for) have narrower scope.
func example() {
x := 5 // x is local to this function
}Re-declaring a variable with := in a nested block creates a new variable with the same name (shadowing the original):
The new declaration creates a separate variable that only exists in that inner scope.
The outer variable is not modified; it’s simply inaccessible while you're in the inner scope.
camelCase for variablesAsk the AI if you need help understanding or want to dive deeper in any topic