dongzhan1878
2017-10-28 14:44
浏览 584
已采纳

将array转换为interface {}进行切片,但结果不能使用len()和其他方法

I tried :

var a [100]int
func fun1(src interface{}) interface{} {
    src, _ = src.([100]int) // changed []int to [100]int
    fmt.Println(reflect.TypeOf(src)) // result: []int
    dest := make([]int, len(src))
    return dest
}

there is an error:

message: 'invalid argument src (type interface {}) for len'

But if I redefine a variable:

var a [100]int
func fun1(src interface{}) interface{} {
    slice_src, _ := src.([100]int) //changed []int to [100]int
    fmt.Println(reflect.TypeOf(slice_src)) // result: []int
    dest := make([]int, len(slice_src))
    return dest
}

it will be ok.

why reflect.TypeOf(src) will print []int after I used src.([]int) but error shows src is still interface{} ? I have checked this convert interface{} to int, but I still don't understand how to use correct conversion.

There is another question:

I changed the []int to [100]int since the type assertion before will return [] and false.

But if I don't know the type of a, how can I use type assertion to transfer an array (like[99]int) as a interface{} to function and return slice ([]int)?

图片转代码服务由CSDN问答提供 功能建议

我尝试过:

  var a [100] int \  nfunc fun1(src interface {})interface {} {
 src,_ = src。([100] int)//将[] int更改为[100] int 
 fmt.Println(reflect.TypeOf(src))  //结果:[] int 
 dest:= make([] int,len(src))
 return dest 
} 
   
 
 

错误:

 消息:'len的无效参数src(类型为{}的接口)'
   
 
 

我重新定义了一个变量:

  var a [100] int 
func fun1(src interface {})interface {} {
 slice_src,_:= src。([100  ] int)//将[] int更改为[100] int 
 fmt.Println(reflect.TypeOf(slice_src))//结果:[] int 
 dest:= make([] int,len(slice_src))  
返回目标
} 
   
 
 

没关系。

为什么 reflect.TypeOf(src) 将在我使用 src之后打印[] int。([] int),但错误显示src仍然是界面{}? 我已经检查了此,但我仍然不了解如何使用正确的转换。

还有另一个问题:

我将 [] int 更改为 [100] int ,因为之前的类型声明将返回 [] false

但是,如果我不知道 a 的类型,该如何使用类型断言来传输数组(例如 [99] int < / code>)作为 interface {} 起作用并返回slice( [] int )?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • douhuiyan2772 2017-10-28 14:55
    已采纳

    when you first declare src, in fun1(src interface{}) you are making a variable of type interface. Which, of course cannot have len called on it.

    The reason reflect.TypeOf says []int is due to how TypeOf works. It takes an interface{} and tells you the type of the thing in the interface{}

    so, in the first example, you already had an interface and in the second example, go automatically created an interface{} instance to hold your []int slice.

    评论
    解决 无用
    打赏 举报
查看更多回答(2条)

相关推荐 更多相似问题