Learn

We can use functions to capture logic involving our structs and simplify it.

Structs will often have important operations that can be performed on them. For example, with a struct representing a geometric shape, it would be natural to have functions that compute its area and perimeter.

Let’s say we have a struct describing a rectangle. The rectangle struct will contain two fields: the length and the width. We define this struct:

type Rectangle struct { length float32 width float32 }

We can define a function that computes the area of the rectangle; the product of the length and the width.

func (rectangle Rectangle) area() float32{ return rectangle.length * rectangle.height }

The key thing to notice is the line (rectangle Rectangle). This line signals to Go that the area() function belongs to the Rectangle struct. Note that functions associated with a struct are written outside of the struct!

If we have an instance of Rectangle called rect, we can call the area() function like so:

rect.area()

Defining a function in this way will only pass in a copy of the rectangle: that is, we will not be able to use the function to alter the value of a field!

If we want to write a function that allows us to modify the value of a struct field, we have to pass in a pointer to a struct. We will see how this works in the next exercise.

Before we modify our structs in functions, let’s practice writing basic struct functions!

Instructions

1.

Given the struct Triangle which represents a triangle by its base and height, write an associated function called area() that computes the area of a triangle. The area of a triangle is of type float32

The formula for the area of a triangle is:

Area=12(baseheight)Area = \frac{1}{2}(base * height)
2.

In main(), call the area() function and print the result.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?