教程集 www.jiaochengji.com
教程集 >  Golang编程  >  golang教程  >  正文 Golang - 如何将interface{}转换为slice遍历

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

发布时间:2023-03-18   编辑:jiaochengji.com
教程集为您提供Golang - 如何将interface{}转换为slice遍历等资源,欢迎您收藏本站,我们将为您提供最新的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 - 如何将interface{}转换为slice遍历”的文章就介绍到这了,更多文章或继续浏览下面的相关文章,希望大家以后多多支持JQ教程网!

您可能感兴趣的文章:
浅析 golang interface 实现原理
Golang面试题解析(五)
理解 Go 编程中的 slice
Golang 中使用 Slice 索引 Map 替代 Map 获得性能提升
活学活用golang的反射机制
golang key map 所有_Golang面试知识点总结
【GoLang】golang底层数据类型实现原理
golang 初始化并赋值_Golang | 既是接口又是类型,interface是什么神仙用法?
[go语言]-slice实现的使用和基本原理
golang 模板(template)的常用基本语法

[关闭]
~ ~