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

将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)?

  • 写回答

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条)

报告相同问题?

悬赏问题

  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决