Type of generic type

Hi everybody

I’m trying to write a library for Option types with the new generic approach, which is a valid thing to do with generics I think.

I want to be able to use these data-types in models, therefore the method Scan and Value should be implemented. Here is my code for the struct:

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

This is my approach for the scan method. Now only int64 is implemented but of course I want more data-types to be implemented

func (o *Option[T]) Scan(value any) error {
	if reflect.TypeOf(value) == nil {
		*o = Option[T]{}
		return nil
	switch reflect.TypeOf(value) {
	case reflect.TypeOf(int64(0)):
		var i sql.NullInt64
		if err := i.Scan(value); err != nil {
			return err
		if i.Valid {
			*o = Option[int64]{
				value:  int64(i.Int64),
				isSome: true,
		} else {
			*o = Option[T]{}

	return nil

This code does not compile because I can’t assign Option[int64] to o which makes sence to me. But how can I create a generic function like this then?

Hi @Michael_Hugi,

The idea behind a generic function is that it can apply uniform operations on the parameter without knowing the exact type. If the function body needs to drill down to the actual type of a parameter, the function cannot considered generic anymore. Hence I don’t think that type parameters can help to achieve what you want. Dealing with unknown types at runtime usually is the realm of empty interfaces and reflection.

(But I would be happy to be proven wrong. I am not that deep into generics yet and am sure there are still a few generics constructs to be discovered.)

1 Like

Can you show an example of how you’d plan on using this?

Yes here is an example

sentTime := Option[time.Time]{

db.QueryRow("SELECT sent_time from mail_sender").Scan(&sentTime)

if (sentTime.IsNone(){
    //Send mail

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