Documentation
¶
Overview ¶
Package result provides a simple result, wrapping either a value or an error.
Main use case is to send it over channels, when possible errors should be propagated to the receiver.
Apart from that, after calling `Get()`, it can be used with go's idiomatic error handling, like:
value, err := result.Get()
if err != nil {
// handle error
}
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Result ¶
type Result[T any] struct { // contains filtered or unexported fields }
Result wraps a value or an error.
func Of ¶
Of creates a new Result with the given value and error.
Example ¶
package main
import (
"bufio"
"fmt"
"io"
"github.com/KrischanCS/go-toolbox/result"
)
func main() {
resultChan := make(chan result.Result[int])
go func() {
resultChan <- result.Of(getValue(1))
resultChan <- result.Of(getError(io.EOF))
resultChan <- result.OfValue(2)
resultChan <- result.OfError[int](bufio.ErrFinalToken)
close(resultChan)
}()
for res := range resultChan {
v, err := res.Get()
if err != nil {
fmt.Println("Got error:", err)
continue
}
fmt.Println("Got value:", v)
}
}
func getValue(i int) (int, error) {
return i, nil
}
func getError(err error) (int, error) {
return 0, err
}
Output: Got value: 1 Got error: EOF Got value: 2 Got error: final token
func (Result[T]) Must ¶
func (r Result[T]) Must() T
Must returns the value of the Result and panics if the Result contains an error.
Not recommended for production code, but can be useful in tests or small scripts/playground projects.
Example ¶
package main
import (
"fmt"
"io"
"github.com/KrischanCS/go-toolbox/result"
)
func main() {
resultSuccess := result.Of(getValue(1))
fmt.Println(resultSuccess.Must())
func() {
defer func() {
v := recover()
if v != nil {
fmt.Println("Panicked:", v)
}
}()
resultError := result.Of(getError(io.EOF))
fmt.Println(resultError.Must())
}()
}
func getValue(i int) (int, error) {
return i, nil
}
func getError(err error) (int, error) {
return 0, err
}
Output: 1 Panicked: Must called on result with error: [*errors.errorString]: EOF
func (Result[T]) String ¶
String returns a string in the format:
- If Successful Result: "(Result[{{type}}]: '{{value}}')"
- If error Result: "(Result[{{type}}]: <error[{{error type}}]: {{error}}>)"
Example ¶
package main
import (
"fmt"
"io"
"github.com/KrischanCS/go-toolbox/result"
)
func main() {
resultSuccess := result.Of(getValue(1))
resultError := result.Of(getError(io.EOF))
fmt.Println(resultSuccess.String())
fmt.Println(resultError.String())
}
func getValue(i int) (int, error) {
return i, nil
}
func getError(err error) (int, error) {
return 0, err
}
Output: (Result[int]: 1) (Result[int]: <error[*errors.errorString]: EOF>)
Click to show internal directories.
Click to hide internal directories.