devshoe
devshoe

Reputation: 21

How to get a new instance of the type that implemented a particular interface

I declare an interface like this:

type TimeIndexedTable interface {
    Get(string) ([]float64, error)
    Set(string, []float64) error
    GetIndex() []time.Time
    SetIndex([]time.Time)
    ListColumns() []string
}

And then I want to implement a function called Resample

Resample(**UNDERLYING** TimeIndexedTable, interval time.Duration, functionMap map[string]string)(TimeIndexedTable ,error){
//give me a new instance of the UNDERLYING
}

So, I would like to know how to get the UNDERLYING type and initialize an empty instance of it.

I apologize if this question is confusing or has been asked before, but I have looked.

Upvotes: 2

Views: 56

Answers (1)

user12258482
user12258482

Reputation:

Use reflect.New to create a new value of the type.

func Resample(src TimeIndexedTable, interval time.Duration, functionMap map[string]string)(TimeIndexedTable ,error){

    t := reflect.TypeOf(src)
    var v reflect.Value

    if t.Kind() == reflect.Ptr {
        // The interface is on the pointer receiver. 
        // Create a pointer to a new value.
        v = reflect.New(t.Elem())
    } else {
        // The interface is on the value receiver. 
        // Create a new value.
        v = reflect.New(t).Elem()
    }

    // Get the value as a TimeIndexedTable using a type assertion.
    dst := v.Interface().(TimeIndexedTable)

    ...

Run it on the playground

Upvotes: 3

Related Questions