Course outline
Course / The terminal and the language

Fix the shadow

Lab

How to fetch and submit this lab

Once: install the tool and connect your account.

curl -fsSL https://gonomicon.com/install.sh | sh
gonomicon login

Each 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 submit

Go installed? gonomicon test runs the visible test on your computer first. Submitting also runs hidden checks on our server.

Goal 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. SumMultiples already has real logic, but a shadowing bug just like the lesson's example. Raise has a // TODO comment and a return line you will change.
  • In SumMultiples, find the line that shadows total with := instead of updating it, and fix it so the outer total actually accumulates. Remove the line that only exists to keep the broken version compiling.
  • SumMultiples(limit) should sum every whole number below limit that is a multiple of 3 or 5. A number that is a multiple of both (like 15) is only added once.
  • In Raise, return score raised by percent percent: score plus percent percent of score. Don't try to change the caller's variable through the parameter — Go passes a copy, so the only way out is to return the 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

  1. 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.
  2. 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.
  3. 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

Something wrong with this lesson? Report a problem