Go Variables

Declaring Variables

Variables in Go are declared using the var keyword:

var age int
var name string = "Alice"
var ready = true // inferred type

Short Declaration (:=)

Inside functions, you can use := to declare and initialize a variable in one step:

Loading...
Output:

This is the most common way to create variables inside a function body.

Multiple Declarations

You can group variable declarations for cleaner code:

var (
  title string
  price float64
  inStock bool
)

Constants

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.

Scope

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
}

Shadowing

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.

Loading...
Output:

Naming Conventions

  • Use camelCase for variables
  • Avoid underscores or capitalized local variables
  • Exported variables must start with an uppercase letter

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic