Skip to content

Commit

Permalink
Readme edit.
Browse files Browse the repository at this point in the history
  • Loading branch information
lunemec committed Nov 2, 2022
1 parent 0b64775 commit e46ce4a
Showing 1 changed file with 52 additions and 0 deletions.
52 changes: 52 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,58 @@ func main() {
}
```

## Example using generics
```go
package main

import (
"fmt"

"github.com/lunemec/as"
)

func main() {
for _, n := range []int{127, 128} {
num, err := as.T[int8](n)
if err != nil {
fmt.Printf("Input invalid: %d, err: %s\n", num, err)
} else {
fmt.Printf("Input valid: %d\n", num)
}
}
// Output: Input valid: 127
// Input invalid: -128, err: 128 (int) overflows int8
}
```

## Example slices type conversion with overflow check
```go
package main

import (
"fmt"

"github.com/lunemec/as"
)

func main() {
out, err := as.SliceT[int, int8]([]int{127, 128})
fmt.Printf("Output: %+v, error: %+v\n", out, err)
// Output: Output: [127 0], error: 1 error occurred:
// * at index [1]: 128 (int) overflows int8
}
```

## Other considerations
Note this checking is not free, check benchmarks for each checked cast.

There are several [Go proposals](https://github.com/golang/go/issues/30613) to have this functionality in the language
but many of them even predate this library.


There are also [libraries](https://github.com/JohnCGriffin/overflow) that
allow for math operations while checking for overflow at the output.

## Architecture support
`As` currently supports these architectures and correctly handles overflows for 64/32 bit numbers:
* 386
Expand Down

0 comments on commit e46ce4a

Please sign in to comment.