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?