5. Append

Append

The built-in append function is used to dynamically add elements to a slice:

func append(slice []Type, elems ...Type) []Type

If the underlying array is not large enough, append() will create a new underlying array and point the returned slice to it.

circle-info

Notice that append() is variadic, the following are all valid:

slice = append(slice, oneThing)
slice = append(slice, firstThing, secondThing)
slice = append(slice, anotherSlice...)

Assignment

We've been asked to add a feature that extracts costs for a given day.

Complete the getDayCosts() function using the append() function. It accepts a slice of cost structs and a day int, and it returns a float64 slice containing that day's costs. A day may have multiple costs.

If there are no costs for that day, return an empty, non-nil slice.

Solution

main.go
package main

type cost struct {
	day   int
	value float64
}

func getDayCosts(costs []cost, day int) []float64 {
	sol := []float64{}
	for count := 0; count < len(costs); count++ {
		if costs[count].day == day {
			sol = append(sol, costs[count].value)
		}
	}
	return sol
}

Go Structs Explained

What is a Struct?

A struct in Go is a data structure that groups together related fields. It's similar to a dictionary in some ways, but it's more structured and type-safe.

Defining a Struct

This defines a blueprint for a cost. Each cost has exactly two fields:

  • day (an integer)

  • value (a float64)

Think of it like a form with two labeled boxes.

Creating a Struct Instance

Here's an example of what one cost looks like:

This creates a single cost where day is 1 and value is 2.0.

Accessing Struct Fields

To access the values, you use dot notation:

  • c.day gives you 1

  • c.value gives you 2.0

Slices of Structs

In your function, costs is a slice (like an array) of these cost structs.

To access them:

  • costs[0] is the first cost struct

  • costs[1] is the second cost struct

  • costs[0].day is the day from the first cost (returns 0)

  • costs[0].value is the value from the first cost (returns 1.0)

  • costs[2].value is the value from the third cost (returns 3.1)

Visual Example

Looking at test input:

How the Loop Works

  • count = which position in the slice you're currently at (0, 1, 2, 3...)

  • costs[count] = the entire cost struct at that position

  • costs[count].day = the day field from that cost

  • costs[count].value = the value field from that cost