Error handling with generics

Hi everyone

I’m trying the new beta 1.18.1 with generics. I have a function that returns a generic type but can also return an error.
In case I return an error, i need to provide a tuple of a value of generic and an error. How can I create a generic value?

Here is my attempt:

type Option[T any] struct {
	value  T
	isSome bool

// Val returns the value or default and error if represents null
func (o Option[T]) Val() (T, error) {
	if !o.isSome {
		return T{}, errors.New("Opt is none")
	return o.value, nil

1 Like
	if !o.isSome {
		var t T
		return t, errors.New("Opt is none")

A bit verbose for my taste, but it works. Have tried it with Option[string], Option[int] and Option[bool], I assume that more complex types would work as well.


Error handling in go is verbose in general.
Thanks for the answer. Works!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.