Check Type without generic

Hi

I have a small library with a struct Option[T]. Is there a way to check if an object is an instance of Option without it’s generic type, cast it and get it’s inner type?

package main

type Option[T] struct{
    Value       T
    IsSome    bool
}

func (o Option[T]) InnerType() reflect.Type {
	return reflect.TypeOf((*T)(nil)).Elem()
}

This works so far. What I want to achieve is:

func IsOption(o any) bool {
	??
}

func GetInnerType(o any) *reflect.Type {
	if !IsOption(o) {
		return nil
	}
	opt := o.(Option)
	typ := opt.InnerType()
	return &typ
}


An ugly hack, but “a way”:
strings.HasPrefix(reflect.TypeOf(o).String(),"main.Option[").

1 Like

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