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
Kilogramsbased onfloat64. - Implement
ConvertPoundsToKilogramswhich converts pounds to kilograms (1 kg ≈ 2.20462 lbs). - Implement the
Stringmethod for theKilogramstype to format the output as "X.XX kg". - Ensure the
Stringmethod is correctly associated with theKilogramstype.
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
Stringmethod should format the output to two decimal places. - Input to
ConvertPoundsToKilogramswill always be afloat64. - The
Kilogramstype is based onfloat64.
Notes
- Remember to define the
Stringmethod for your custom type. The method signature should be(Kilograms) String() string. - Use the
fmt.Sprintffunction for formatting the output string. - Consider using the
math.Roundfunction 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.