You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
It would be nice to have a specific type for the pair (type, error), so as to be treated as a normal parameter.
It would allow, for instance, to simplify error chaining, as follows:
package main
import (
"errors"
"fmt"
)
func f(foo int) (int, error) {
if foo > 100 {
return -1, errors.New("error")
}
return 5, nil
}
// I created this type that would be the nice one to have to represent an error OR a value
type TypeOrError[T any] struct {
Error error
Value T
}
func mapError[T any, D any](t TypeOrError[T], gFunc func(T) (*D, error)) (*D, error) {
if t.Error != nil {
return nil, t.Error
}
stringResult, err := gFunc(t.Value)
if err != nil {
return nil, err
}
return stringResult, nil
}
func g(foo int) (*string, error) {
if foo > 10 {
return nil, errors.New("error")
}
s := fmt.Sprintf("%d", foo)
return &s, nil
}
func main() {
mystring, err := mapError[int, string](f(3), g)
// Here `err` may come both for f and g
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Println(mystring)
}
}
That would allow to convert "result or error" into a functor and would greatly simplify the error management.
The text was updated successfully, but these errors were encountered:
@seankhliao in the end it has not to be necessarily an object. It would be just enough to allow functions to pass a result and an error. All in all, it would be nice if I could do mapError[int, string](f(3), g), for instance by accepting something like mapError[T any, D any](T t, err errror, gFunc func(T) (*D, error)) (*D, error)
Proposal Details
It would be nice to have a specific type for the pair (type, error), so as to be treated as a normal parameter.
It would allow, for instance, to simplify error chaining, as follows:
That would allow to convert "result or error" into a functor and would greatly simplify the error management.
The text was updated successfully, but these errors were encountered: