Knaph

First Contact3 of 621 min read

Variables

Go is statically typed — every variable has a fixed type, checked at compile time, not at runtime. Coming from Python, this is the biggest day-to-day difference you'll feel, so let's get comfortable with it immediately.

Declaring variables

The explicit form:

var age int = 34
var name string = "Haleh"
Go

You'll rarely write it that way inside a function, though. Go infers the type from the value, so this is equivalent and far more common:

age := 34
name := "Haleh"
Go

:= declares and initializes in one step. It only works for a brand-new variable inside a function — you can't use it to declare package-level variables, and you can't use it to reassign an existing one (use plain = for that).

age := 34
age = 35   // reassignment, no :=
Go

Try mixing types where Go doesn't expect them:

age := 34
age = "thirty-five"
Go
./main.go:6:7: cannot use "thirty-five" (untyped string constant) as int value in assignment

That's the compiler catching a bug that, in Python, wouldn't surface until the line actually ran — possibly in production, possibly much later than the line that caused it.

Naming and exporting

Go doesn't have public/private keywords. Instead, capitalization controls visibility:

var ExportedName = "visible outside this package"
var unexportedName = "only visible inside this package"
Go

An identifier starting with an uppercase letter is exported (importable by other packages); lowercase means package-private. You'll see this rule everywhere once you know it's there — it's why standard library functions like fmt.Println and strings.Split are capitalized. This rule isn't just for variables — it applies the same way to functions, types, and constants, which you'll meet next.

Test your understanding

Sign in to test your understanding of this lesson and track your progress.

Ask an AI

Open a ready-made prompt in ChatGPT or Claude — just press Enter.