go - 如何获取实现特定接口的类型的新实例
问题描述
我声明一个这样的接口:
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类型并初始化它的空实例。
如果这个问题令人困惑或以前曾被问过,我深表歉意,但我已经看过了。
解决方案
使用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)
...
推荐阅读
- c++ - Mongocxx 库分段错误
- mongodb - 如何在mongodb中根据数组对象键值查找记录?
- python - 连接两列
- laravel - 在外部 php 网站上获取 laravel 当前用户
- javascript - 返回承诺而不是数据
- php - Codeigniter 4 - 如何自动加载自定义配置文件?
- wpf - WPF:如何在我的列表视图项单击中绑定来自 MouseLeftButtonUp 事件的 m 对象属性
- python-3.x - 如何忽略关键错误并继续 while 循环
- google-apps-script - 当用户删除电子表格插件时,随插件添加的文档属性存储是否继续保留?
- javascript - 无法在 Three.js 中加载本地纹理,在 vue.js 中运行三个作为组件