首页 > 解决方案 > Golang改变指针接口的类型

问题描述

我有一个函数,它返回某个接口的一部分指针。我想稍后在代码中将类型更改为实现类型,但没有任何效果,我仍然得到一个无效的类型断言。

例子

func Test(c Parsable)([]*Parsable, error) {
   // generate slice by factory method on Parsable inteface and return slice
}

var implParsable ImplParsable
results, err := Test(implParsable) 

data := results[0].(ImplParsable) // I tried this in many variations but nothing works

标签: go

解决方案


resultSets[0]是指向接口的指针,因此您需要取消引用该指针以获取接口值,您可以内联执行此操作,因为切片值是可寻址的。

data :=  (*resultSets[0]).(ImplParsable)

推荐阅读