Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Proposal: Use Generics for create decimals #382

Open
marlonbarreto-git opened this issue Aug 8, 2024 · 0 comments
Open

Proposal: Use Generics for create decimals #382

marlonbarreto-git opened this issue Aug 8, 2024 · 0 comments

Comments

@marlonbarreto-git
Copy link

Hello,

I’d like to propose an enhancement to the decimal package. Currently, there are several functions like NewFromInt, NewFromInt64, NewFromUint64, etc., which create a Decimal from different numeric types.

I suggest creating a single function, NewFromNumber, that uses Golang’s generics to handle the creation of a Decimal from any numeric type. This would simplify the API and make it more flexible.

Example:

amountDecimal := decimal.From(200.01)

productsDecimal := decimal.From(27)

type CustomNumber int64

customDecimal := decimal.From(CustomNumber(123))

Implementation proposal:

package types

type (
	// Natural represents a natural number.
	// A natural number is a non-negative integer.
	// {0, 1, 2, 3, ...}
	Natural interface {
		~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr
	}

	// Integer represents an integer number.
	// An integer is a number that can be written without a fractional component.
	// {..., -2, -1, 0, 1, 2, ...}
	Integer interface {
		~int | ~int8 | ~int16 | ~int32 | ~int64
	}

	// Float represents a floating-point number.
	// A floating-point number is a number that has a fractional part.
	// {..., -0.2, -0.1, 0.0, 0.1, 0.2, ...}
	Float interface {
		~float32 | ~float64
	}

	// Number represents a number.
	// A number is a mathematical object used to count, measure, and label.
	Number interface {
		Integer | Natural | Float
	}
)
package decimal

func From[N types.Number](rawNumber N) Decimal {
    // Create a decimal by number type
}

Benefits:

  • Simplicity: Reduces the number of functions in the API.
  • Flexibility: Allows for easier extension and usage with any numeric type.
  • Maintainability: Makes the codebase cleaner and easier to maintain.

Impact:

This change would be backward compatible if the existing functions remain. However, over time, users could migrate to the new, more generic function.

I’m open to feedback and would be happy to contribute a PR if the maintainers agree this is a useful addition.
Thank you for considering this suggestion!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant