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

你可能感兴趣的:(Golang)