Constants and Zero Values
Locked In
Last lesson you used :=, Go's shorthand. There's also the var keyword:
var name string = "Gopher"
var count intvar 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:
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:
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: App Config
Set up an app's config using both var and const.
- Declare a constant
AppNamewith value"LevelUpGo" - Declare a constant
MaxUserswith value100 - Declare a variable
currentUserswith typeint(don't assign a value, let it use its zero value)
Then print exactly:
LevelUpGo: 0/100 users