Hone logo
Hone
Problems

Understanding and Implementing Pointer Receivers in Go

Go's methods can be associated with either value receivers or pointer receivers. Understanding when and why to use pointer receivers is crucial for efficient and correct Go programming, especially when you need to modify the state of a struct. This challenge will guide you through implementing a method using a pointer receiver.

Problem Description

You are tasked with creating a Circle struct and implementing a method called Scale on it. This Scale method should take a float64 factor as input and modify the Radius of the Circle by multiplying it with the given factor. You will need to use a pointer receiver for the Scale method to ensure that the original Circle object's radius is actually changed.

Key Requirements:

  • Define a Circle struct with a single field: Radius (type float64).
  • Implement a method named Scale for the Circle struct.
  • The Scale method must accept one argument: factor (type float64).
  • The Scale method must modify the Radius of the Circle by multiplying it with factor.
  • The Scale method must be defined with a pointer receiver (*Circle).
  • Provide a way to create a new Circle (e.g., a constructor function).

Expected Behavior:

When you call the Scale method on a Circle instance, its Radius should be updated in place.

Examples

Example 1:

Input:
radius := 5.0
c := NewCircle(radius)
factor := 2.0
c.Scale(factor)

Output:
Circle{Radius: 10.0}

Explanation:
A circle with an initial radius of 5.0 is created. The Scale method is called with a factor of 2.0. Since Scale uses a pointer receiver, the original circle's radius is updated to 5.0 * 2.0 = 10.0.

Example 2:

Input:
radius := 10.0
c := NewCircle(radius)
factor := 0.5
c.Scale(factor)

Output:
Circle{Radius: 5.0}

Explanation:
A circle with an initial radius of 10.0 is created. The Scale method is called with a factor of 0.5. The radius is updated to 10.0 * 0.5 = 5.0.

Example 3:

Input:
radius := 0.0
c := NewCircle(radius)
factor := 100.0
c.Scale(factor)

Output:
Circle{Radius: 0.0}

Explanation:
A circle with an initial radius of 0.0 is created. Scaling a radius of 0.0 by any factor will still result in 0.0.

Constraints

  • The Radius will be a non-negative float64.
  • The factor will be a non-negative float64.
  • The precision of float64 should be maintained.

Notes

  • Consider the difference between passing a value and passing a pointer to a struct when defining methods.
  • Why would using a value receiver for Scale not work as intended in this scenario? Think about how Go passes arguments to functions and methods.
  • You might want to create a NewCircle function to easily instantiate Circle structs.
Loading editor...
go