Enforce method on object using Go Generics

Viewed 44

I'm trying to simplify some code using generics. Even though I currently have a bunch of types (A, B, C) that each implement their own data-ingestion, the logic is the same; so I want to combine them using generics.

The general idea is that the data comes in an abstract format, and gets unmarshaled from json into the correct type:

func unmarshalA(json Json) *A {
  rv := &A{}
  Unmarshall(json, rv)
  rv.Validate()
  return rv
}

Of course error handling and the likes is omitted here.

Now since each of these have the same logic, what I'd like to do is the following:

type canBeValidated interface {
  Validate() error
}

func unmarshalType[T canBeValidated](json Json) *T { 
  rv := &T{}
  Unmarshall(json, rv)
  rv.Validate()         // Unresolved Reference: Validate
  return rv
}

So my question then becomes: How do I use generic types (or another solution) to mandate that a type has a particular method; without caring about anything else?

0 Answers
Related