首页 > 解决方案 > 如何获取实现特定接口的类型的新实例

问题描述

我声明一个这样的接口:

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

然后我想实现一个名为 Resample 的函数

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

所以,我想知道如何获取UNDERLYING类型并初始化它的空实例。

如果这个问题令人困惑或以前曾被问过,我深表歉意,但我已经看过了。

标签: go

解决方案


使用reflect.New创建类型的新值。

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)

    ...

在操场上跑


推荐阅读