怎么在Golang中{}将接口转换为数组

  介绍

怎么在Golang中{}将接口转换为数组?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

Golang适合做什么

Golang可以做服务器端开发,但Golang很适合做日志处理,数据打包,虚拟机处理,数据库代理等工作。在网络编程方面,它还广泛应用于网络应用,API应用等领域。

{}转接口为普通类型

Golang{}中界面可以代表任何类型,对于像int64, bool,字符串等这些简单类型,接口{}类型转为这些简单类型时,直接使用

p, ok :=, t。(保龄球)   p, ok :=, t。(int64)

如果好==true的话,就已经类型转换成功。

假设有这样一个场景,我们有一个函数有返回值,但是返回值的类型不定,所以我们的返回值类型只能以接口来代替了。

返回接口类型之后,我们就要对其类型进行判断然后进行类型转换。如果返回的是数组的话,我们就不能像上面那样直接进行转换了。

那有什么办法呢?

可以考虑使用reflect.Typeof (mm) .Kind ()。

func 生成(),(接口{},bool), {//s :=,[]字符串{“123”,,,“345”,,“abc"}//s :=123   s :=,“mmm"   return 年代,真实   }   func 测试(),{   起源、,ok :=,生成()   if  ok  {   switch  reflect.TypeOf(起源).Kind (), {   case  reflect.Slice, reflect.Array:   s :=, reflect.ValueOf(起源)   for 小姐::=,0;,小姐:& lt;, s.Len();,我+ +,{   fmt.Println (s.Index(我))   }   case  reflect.String:   s :=, reflect.ValueOf(起源)   fmt.Println (s.String(),,“小姐:am  a  string  type 变量!”)   case  reflect.Int:   s :=, reflect.ValueOf(起源)   t :=, s.Int ()   fmt.Println (t),“,小姐:am  a  int  type 变量!”)   }   }   }

生成()函数有两个返回值,一个是接口类型,一个是bool类型。

我们只对第一个参数进行处理,首先使用reflect.TypeOf (mm) .Kind()获得mm的类型,然后采用开关语句来判断mm的类型、类型判断完之后进入相应的情况下,然后通过reflect.ValueOf来毫米(mm)的值取出来,如果mm本身是个数组的话,那么年代也是一个数组,就可以进行遍历操作了。

总结

1,对于我们已知返回值是哪种类型的情况下,可以直接将返回值进行类型转换,像上面那种转为普通类型的方法一样。

2,对于返回值类型不是已知的情况下,可以考虑使用reflect.TypeOf()的方式。

<强>补充:{}golang接口转换成结构体结构体的两种方法

1。使用断言,强制转换

,p, ok :=(值)。(用户)   ,,,,if  ok  {   ,,,,,,,,fmt.Println (“id:“, +, p.Id)   ,,,,,,,,fmt.Println(“名字:“,+,p.Name)   ,,,,},{else    ,,,,,,,,fmt.Println(“还要not  convert")   ,,,,}

2。json序列化

resByre, resByteErr:=json.Marshal (ResponseData)中   ,if  resByteErr  !=, nil  {   c.Data才能(utils.ErrorResult(“读取信息失败“,+,resByteErr.Error ()))   ,返回   ,}   var  newData  MnConfig   ,jsonRes:=json.Unmarshal (resByre, newData)   ,if  jsonRes  !=, nil  {   c.Data才能(utils.ErrorResult(“读取信息失败“,+,jsonRes.Error ()))   ,返回   以前,}

实例:

package  main    import  (   ,“编码/json"   ,“fmt"   )   ,   type  user  struct  {   ,Id  int “json:“id"”   ,Name  string “json:“name"”   },   ,   func  main (), {,   ,列出:=用户{   ,,,,,,,   ,,名字:“杉杉“,   ,}   ,   {},var  newInterface1 接口   ,//第,一种使用接口   newInterface1=分类列出   ,fmt.Printf(“使用接口:,% v", newInterface1。(用户))   ,   ,//第二种使用json   {},var  newInterface2 接口   newInterface2=分类列出   ,resByre, resByteErr :=, json.Marshal (newInterface2)   ,if  resByteErr  !=, nil  {   fmt.Printf才能(“% v", resByteErr)   ,返回   ,}   var  newData 用户   ,jsonRes :=, json.Unmarshal (resByre,,, newData)   ,if  jsonRes  !=, nil  {   fmt.Printf才能(“% v", jsonRes)   ,返回   ,}   ,fmt.Printf(“使用,json:, % v", newData)   ,   }

怎么在Golang中{}将接口转换为数组