Hone logo
Hone
Problems

Defining Custom Types in Go

Go's type system allows you to define your own types based on existing ones. This is useful for adding semantic meaning to your code, enforcing constraints, and creating more readable and maintainable programs. This challenge will test your understanding of how to define and use custom types in Go.

Problem Description

You are tasked with creating a custom type called Kilograms based on the float64 type. This type represents a weight in kilograms. You need to implement a function ConvertPoundsToKilograms that takes a float64 representing weight in pounds and returns a value of type Kilograms. Additionally, you need to create a function String for the Kilograms type that returns a string representation of the weight in the format "X.XX kg".

Key Requirements:

  • Define a custom type Kilograms based on float64.
  • Implement ConvertPoundsToKilograms which converts pounds to kilograms (1 kg ≈ 2.20462 lbs).
  • Implement the String method for the Kilograms type to format the output as "X.XX kg".
  • Ensure the String method is correctly associated with the Kilograms type.

Expected Behavior:

The ConvertPoundsToKilograms function should accurately convert pounds to kilograms and return the result as a Kilograms value. The String method should format the Kilograms value to two decimal places followed by " kg".

Edge Cases to Consider:

  • Negative input values for pounds (should still convert correctly, representing a negative weight).
  • Zero input values for pounds (should return 0.00 kg).
  • Large input values for pounds (ensure no overflow issues, although this is less likely with float64).

Examples

Example 1:

Input: 10.0
Output: 4.54 kg
Explanation: 10 pounds is approximately 4.54 kilograms. The String method formats the output correctly.

Example 2:

Input: 0.0
Output: 0.00 kg
Explanation: Zero pounds is zero kilograms. The String method formats the output correctly.

Example 3:

Input: -5.0
Output: -2.27 kg
Explanation: Negative pounds are converted to negative kilograms. The String method formats the output correctly.

Constraints

  • The conversion factor is approximately 2.20462.
  • The String method should format the output to two decimal places.
  • Input to ConvertPoundsToKilograms will always be a float64.
  • The Kilograms type is based on float64.

Notes

  • Remember to define the String method for your custom type. The method signature should be (Kilograms) String() string.
  • Use the fmt.Sprintf function for formatting the output string.
  • Consider using the math.Round function to round the Kilograms value to two decimal places before formatting. This is not strictly required, but it can improve the consistency of the output.
  • Focus on creating a clear and concise solution that demonstrates your understanding of type definitions and method implementations in Go.
Loading editor...
go