From e46ce4a0b4632db1d502098ce4febdfa44bfccdc Mon Sep 17 00:00:00 2001 From: Lukas Nemec Date: Wed, 2 Nov 2022 18:21:23 +0100 Subject: [PATCH] Readme edit. --- README.md | 52 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/README.md b/README.md index 7efa266..14f9bc0 100644 --- a/README.md +++ b/README.md @@ -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