Variables and Constants
Go has three ways to introduce a name, and they are not interchangeable.
constfixes a value at compile time. It can never be reassigned, and it costs nothing at run time.vardeclares a variable, with or without an initial value. Without one it gets that type's zero value.:=declares and assigns in one step, inferring the type. It only works inside a function.
Package-level names must use const or var; := is function-only.
Task
Open main.go and finish three things.
AppNameis a constant string. Give it the value"Gofinity".MaxRetriesis a constant integer. Give it the value3.- Implement
RetryStatus(used int) stringandRemaining(used int) int.
RetryStatus returns one sentence, built from the two constants:
Gofinity: 2 of 3 retries used, 1 remaining
Remaining returns just the number of retries left.
The rules:
- A negative
usedcounts as0.RetryStatus(-4)reports0 of 3 ... 3 remaining. - A
usedaboveMaxRetriescounts asMaxRetries. The sentence must never claim more retries than exist, andRemainingmust never go below0. - Both functions read
MaxRetriesrather than a hard-coded3. Change the constant and every answer should move with it.
Hints
-
const AppName = "Gofinity"is an untyped constant. It has no type until it is used, so it slots into anything a string fits, andMaxRetriesslots into anything an integer fits. That is why you rarely need to writeconst MaxRetries int = 3, though you may. -
Clamping reads well as a small unexported helper both functions call:
func clamp(used int) int { if used < 0 { return 0 } ... }Lowercase means package-private, which is right for something no caller outside this file needs.
-
Inside a function,
spent := clamp(used)is the idiomatic declaration. Savevarfor when you want the zero value or need the type spelled out. -
fmt.Sprintf("%s: %d of %d ...", AppName, spent, MaxRetries, left)builds the sentence. Count your verbs and your arguments: a mismatch shows up as%!d(MISSING)in the output rather than as a compile error.