Constants and Zero Values

Constants and Zero Values

Locked In

Last lesson you used :=, Go's shorthand. There's also the var keyword:

example.go
var name string = "Gopher"
var count int

var lets you spell out the type explicitly. Skip the value, like var count int, and Go gives it a zero value. No uninitialized garbage.

Every type has a zero value:

Type Zero Value
int 0
string ""
bool false
float64 0.0

Why set an explicit type? Sometimes Go's inference picks a type you don't want. For example, := with a number always gives you int, but you might need a smaller type:

example.go
var port uint16 = 8080  // uint16, not int
var ratio float32 = 0.5 // float32, not float64

Now, some values should never change. Think about a max retry limit or your app's name. If someone accidentally reassigns those mid-program, things break in subtle ways. const prevents that at compile time:

example.go
const MaxRetries = 3
const AppName = "LevelUpGo"

MaxRetries = 5 // compile error: cannot assign to MaxRetries

If a value is known at compile time and should stay fixed, use const. The compiler catches mistakes before your code ever runs.

>_Exercise

Exercise: App Config

Set up an app's config using both var and const.

  1. Declare a constant AppName with value "LevelUpGo"
  2. Declare a constant MaxUsers with value 100
  3. Declare a variable currentUsers with type int (don't assign a value, let it use its zero value)

Then print exactly:

example.go
LevelUpGo: 0/100 users
Stuck? Reveal a hint to help you.
Hints (0/3)
Key Takeaway
Next UpMath and type conversions.