Skip to content

proposal: define a type for (type, error) #64377

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
fcracker79 opened this issue Nov 24, 2023 · 3 comments
Closed

proposal: define a type for (type, error) #64377

fcracker79 opened this issue Nov 24, 2023 · 3 comments

Comments

@fcracker79
Copy link

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:

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.

@gopherbot gopherbot added this to the Proposal milestone Nov 24, 2023
@seankhliao
Copy link
Member

Duplicate of #51931

@seankhliao seankhliao marked this as a duplicate of #51931 Nov 24, 2023
@seankhliao seankhliao closed this as not planned Won't fix, can't repro, duplicate, stale Nov 24, 2023
@fcracker79
Copy link
Author

@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)

@seankhliao
Copy link
Member

also declined #40387

@golang golang locked and limited conversation to collaborators Nov 23, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

3 participants