Chapter 8 - Structs

Exercise 1: Defined Types and Structs

Let’s create a struct type named rectangle, that represents rectangular areas. It should have length and width fields, both of type float64.

Also create a rectangleInfo function that accepts a rectangle as a parameter. rectangleInfo should print "Length:" followed by the rectangle’s length, then "Width:" followed by the rectangle’s width.

Finally, in your main function, create a new rectangle value, and set its length and width fields. Then pass the rectangle to rectangleInfo to display its field values.

package main

import "fmt"

// YOUR CODE HERE: Declare a "rectangle" struct type.

// YOUR CODE HERE: Define a rectangleInfo function.

func main() {
	// YOUR CODE HERE: Create a new rectangle, and set its
	// length and width fields. Pass it to rectangleInfo.
}

Sample output:

Length: 4.2
Width: 2.3

When you’re ready, have a look at our solution.

Exercise 2: Modifying Structs from Functions

All squares are rectangles, but not all rectangles are squares… Let’s define a makeSquare function that takes a rectangle and “cuts it down” so that its longer sides are equal to its shorter sides.

  • If the rectangle’s length is greater than its width, set its length equal to its width.
  • Otherwise, set the width equal to the length.

makeSquare won’t return a value; it should modify the rectangle it receives (meaning it will need to accept a pointer to a rectangle and modify the value at that pointer).

In main, create a couple different rectangle values, one where the length is greater and one where the width is greater, and try converting them to squares using makeSquare.

Here’s our solution.