The provided Go code defines a Money type that encapsulates both the amount in cents and its currency, ensuring that operations like addition only proceed if the currencies match. This approach prevents common pitfalls such as accidentally adding amounts in different currencies or losing precision due to floating-point arithmetic.
Here's an overview of the key components:
-
Currency Definition:
Currencyis a string type representing supported currencies (e.g., USD, EUR).- The
ParseCurrencyfunction validates and returns the currency as aCurrencytype if it matches one of the predefined values (USD,EUR, orGBP). If not, an error is returned.
-
Money Type:
Moneystruct contains two fields:cents(an integer representing the amount in cents) andcurrency(a string representing the currency).- The
NewMoneyfunction initializes a newMoneyinstance with given cents and currency, ensuring that both values are valid.
-
Operations:
Add: Adds twoMoneyinstances if they have the same currency.IsNegative: Returns true if the amount is negative (i.e., less than zero).
Read the full article at DEV Community
Want to create content about this topic? Use Nemati AI tools to generate articles, social posts, and more.

![[AINews] The Unreasonable Effectiveness of Closing the Loop](/_next/image?url=https%3A%2F%2Fmedia.nemati.ai%2Fmedia%2Fblog%2Fimages%2Farticles%2F600e22851bc7453b.webp&w=3840&q=75)



