Go · Level 1 Structs

Range and Structs

Apply a percentage discount to every item of a Go slice of structs in place, and learn why changing the range variable changes only a copy.

  • a struct groups named fields
  • range gives a copy of each item
  • change items[i] through the index

A struct groups named fields, like Item{Name: "pen", Price: 100}. Trap: for _, it := range items gives a copy of each item, so changing it.Price changes nothing. Go through the index instead.

for _, it := range items {
    it.Price = 0  // edits a copy
}
for i := range items {
    items[i].Price = 0  // edits the item
}

Write Discount(items []Item, percent int): lower every price in place by percent, rounded down to the cent. Example: 10% off {pen 100} makes it {pen 90}.

solution.go
Test Suites Pending
Output