-
Notifications
You must be signed in to change notification settings - Fork 30
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge branch 'master' into refactor-how-we-calculate-time
- Loading branch information
Showing
4 changed files
with
53 additions
and
8 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
package typing | ||
|
||
import "fmt" | ||
|
||
func AssertType[T any](val any) (T, error) { | ||
castedVal, isOk := val.(T) | ||
if !isOk { | ||
var zero T | ||
return zero, fmt.Errorf("expected type %T, got %T", zero, val) | ||
} | ||
return castedVal, nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
package typing | ||
|
||
import ( | ||
"testing" | ||
|
||
"github.com/stretchr/testify/assert" | ||
) | ||
|
||
func TestAssertType(t *testing.T) { | ||
{ | ||
// String to string | ||
val, err := AssertType[string]("hello") | ||
assert.NoError(t, err) | ||
assert.Equal(t, "hello", val) | ||
} | ||
{ | ||
// Int to string | ||
_, err := AssertType[string](1) | ||
assert.ErrorContains(t, err, "expected type string, got int") | ||
} | ||
{ | ||
// Boolean to boolean | ||
val, err := AssertType[bool](true) | ||
assert.NoError(t, err) | ||
assert.Equal(t, true, val) | ||
} | ||
{ | ||
// String to boolean | ||
_, err := AssertType[bool]("true") | ||
assert.ErrorContains(t, err, "expected type bool, got string") | ||
} | ||
} |