Course / The terminal and the language
Fix the shadow
How to fetch and submit this lab
Once: install the tool and connect your account.
curl -fsSL https://gonomicon.com/install.sh | sh
gonomicon loginEach lab: download it, edit the file named in the instructions, then submit.
gonomicon fetch week-1/12-06-fix-the-shadow
cd 12-06-fix-the-shadow
gonomicon submitGoal
SumMultiples has a shadowing bug: fix it so it actually sums the multiples of 3 or 5 below limit. Then write Raise from scratch, returning a score raised by a percentage.
Example The lesson's own shadowing bug looked like this:
total := 0
for i := 1; i <= 3; i++ {
total := total + i
fmt.Println("inner total:", total)
}
fmt.Println("outer total:", total)
inner total: 1
inner total: 2
inner total: 3
outer total: 0
total := total + i makes a brand-new total on every pass, so the outer total is never touched. The fix is one character: total = total + i (or total += i).
Rules
- Edit
shadow.go.SumMultiplesalready has real logic, but a shadowing bug just like the lesson's example.Raisehas a// TODOcomment and a return line you will change. - In
SumMultiples, find the line that shadowstotalwith:=instead of updating it, and fix it so the outertotalactually accumulates. Remove the line that only exists to keep the broken version compiling. SumMultiples(limit)should sum every whole number belowlimitthat is a multiple of3or5. A number that is a multiple of both (like15) is only added once.- In
Raise, returnscoreraised bypercentpercent:scorepluspercentpercent ofscore. Don't try to change the caller's variable through the parameter — Go passes a copy, so the only way out is toreturnthe new value. - Do not change either function's signature.
What you'll practice Spotting and fixing a real shadowing bug, and writing a function that returns a new value instead of trying to mutate its parameter.
Run it
gonomicon fetch week-1/12-06-fix-the-shadow
cd 12-06-fix-the-shadow
gonomicon test
gonomicon submit
Hints
- In SumMultiples, the line total := total + n inside the loop is the bug: := always makes a brand-new variable, so that inner total vanishes at the end of each pass and the outer total is never touched. Change it to = (or +=) to update the existing total instead.
- For Raise, you don't need to touch the parameter at all. Just compute the raised value and return it: score plus score times percent divided by 100.
- SumMultiples: change "total := total + n" to "total += n" (or "total = total + n"), and delete the now-unneeded "_ = total" line. Raise: return score + score*percent/100