Menu
Coddy logo textTech

Recap - Struct Behavior

Part of the Logic & Flow section of Coddy's GO journey — lesson 11 of 68.

challenge icon

Challenge

Easy

In this challenge, you'll practice implementing both value and pointer receivers by creating a simple rectangle management system. You'll create a Rectangle struct and define two different types of methods that demonstrate when to use each receiver type.

You will receive three inputs:

  • A string representing the rectangle's width (e.g., "5.0")
  • A string representing the rectangle's height (e.g., "3.0")
  • A string representing a scaling factor (e.g., "2.0")

Your task is to:

  1. Define a Rectangle struct with two fields: Width (float64) and Height (float64)
  2. Create a method called area with a value receiver that calculates and returns the area of the rectangle (width × height)
  3. Create a method called scale with a pointer receiver that multiplies both width and height by the given scaling factor
  4. Parse the inputs to create a Rectangle instance
  5. Print the initial area using the format: "Initial area: [area]"
  6. Call the scale method with the scaling factor
  7. Print the scaled area using the format: "Scaled area: [area]"

The area values should be displayed as whole numbers when they are integers (e.g., 15 instead of 15.0), but with decimal places when necessary (e.g., 15.5). This challenge demonstrates the key principle: use value receivers for methods that only read data (like calculating area) and pointer receivers for methods that modify the original struct (like scaling dimensions).

Try it yourself

package main

import (
	"fmt"
	"strconv"
)

// TODO: Define your Rectangle struct here

// TODO: Implement the area method with value receiver here

// TODO: Implement the scale method with pointer receiver here

func main() {
	// Read input
	var widthStr string
	var heightStr string
	var scaleStr string
	fmt.Scanln(&widthStr)
	fmt.Scanln(&heightStr)
	fmt.Scanln(&scaleStr)
	
	// Parse inputs to float64
	width, _ := strconv.ParseFloat(widthStr, 64)
	height, _ := strconv.ParseFloat(heightStr, 64)
	scaleFactor, _ := strconv.ParseFloat(scaleStr, 64)
	
	// TODO: Create Rectangle instance and implement the solution below
	
	// Print initial area
	// fmt.Printf("Initial area: %.0f\n", initialArea) // Use this format for output
	
	// Scale the rectangle
	
	// Print scaled area
	// fmt.Printf("Scaled area: %.0f\n", scaledArea) // Use this format for output
}

All lessons in Logic & Flow