Golang - 如何将interface{}转换为slice遍历

今天写代码时需要把interface{}转为数组并遍历,于是使用断言:

func (cd *commandDefinition) tableOutputForGetCommands(obj interface{}) {
	ele, ok := obj.([]interface{})  
	//cannot use dataSlice (type []common.TableOutput) as type []interface {} in assignment
}

岂料直接panic了。

原来,断言时数组不能直接转为[]interface{}。

让我们重新审视[]interface{}的含义:一个slice,其中每个元素都实现了空的接口。interface{}不是一个确定的类型。每个interface{}占用的内存空间是2 words,一个word存储对应的类型,另一个存对应数据的指针或数据。而常规的Slice,其中每个元素占用的空间不定,由其中元素的类型而定。

所以,不能直接利用断言转为slice。

有什么办法能够解决这个问题呢?反射。

正确的做法是利用反射先遍历slice的值,再进行类型转换。

话不多说上代码:

func (cd *commandDefinition) tableOutputForGetCommands(obj interface{}) {
  var list []common.TableOutput
  if reflect.TypeOf(obj).Kind() == reflect.Slice {
		s := reflect.ValueOf(obj)
		for i := 0; i < s.Len(); i++ {
			ele := s.Index(i)
			list = append(list, ele.Interface().(common.TableOutput))
		}
	} 
}

参考链接:
Github Golang Wiki
StackOverFlow

  • 6
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值