Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions conversion.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ import (
// - If the conversion is not possible for the desired type, an [ErrUnsupportedConversion] error is wrapped in the returned error.
// - If the conversion fails from string, an [ErrStringConversion] error is wrapped in the returned error.
// - If the conversion results in an error, an [ErrConversionIssue] error is wrapped in the returned error.
func Convert[NumOut Number](orig any) (converted NumOut, err error) {
switch v := orig.(type) {
func Convert[NumOut Number, NumIn Input](orig NumIn) (converted NumOut, err error) {
switch v := any(orig).(type) {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What if orig is of a type A declared as type A int? In that case, A satisfies Input so it compiles, but I believe this switch statement won't find a match and hence this function returns an error.

Copy link
Owner Author

@ccoVeille ccoVeille Feb 15, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, it's the first step of a refactoring.

Here I'm only applying a part of the refactoring that need to be done.

I'm only addressing the "the function accepts any" issue that you raised a few weeks ago.

I still have to deal with "type alias are not working" issue. See #72

I have code ready locally.

But I wanted this PR first.

case int:
return convertFromNumber[NumOut](v)
case uint:
Expand Down Expand Up @@ -58,7 +58,7 @@ func Convert[NumOut Number](orig any) (converted NumOut, err error) {
}

// MustConvert calls [Convert] to convert the value to the desired type, and panics if the conversion fails.
func MustConvert[NumOut Number](orig any) NumOut {
func MustConvert[NumOut Number, NumIn Input](orig NumIn) NumOut {
converted, err := Convert[NumOut](orig)
if err != nil {
panic(err)
Expand Down
2 changes: 1 addition & 1 deletion conversion_64bit_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ func TestToInt_64bit(t *testing.T) {
func TestConvert_64bit(t *testing.T) {
t.Run("to uint32", func(t *testing.T) {
for name, tt := range map[string]struct {
input any
input uint64
want uint32
}{
"positive out of range": {input: uint64(math.MaxUint32 + 1), want: 0},
Expand Down
Loading