doulin6761 2015-09-27 11:24
浏览 143
已采纳

golang [] interface {}是否不能用作函数参数? [重复]

This question already has an answer here:

My code :


package sort_test

type SortList []interface{}

type SortFunc func(interface{}, interface{}) bool


func Do(list SortList, function SortFunc)

main package


package main

import (
        "sort_test"
)

func main() {

    list := []int{3, 4, 5, 6, 6, 77, 4, 4, 5, 6, 8, 345, 45, 424, 2, 67, 7, 830}

slice := list[:]

sort_test.Do(slice, function)
}

compile error

src/algorithm/algorithm.go:32: cannot use slice (type []int) as type sort_test.SortList in argument to sort_test.Do
src/algorithm/algorithm.go:32: cannot use function (type func(int, int) bool) as type sort_test.SortFunc in argument to sort_test.Do
make: *** [algorithm] Error 2
</div>
  • 写回答

2条回答 默认 最新

  • drwj4061 2015-09-27 12:36
    关注

    Cannot. Interface is interface.

    interface{} is not some kind of "any" type. But, any type implements interface{}. Interface is just a set of methods which should be implemented.

    If you want to check whether the interface{} is slice or not, you can write it like this:

    import "reflect"
    
    t := reflect.TypeOf(list)
    if t.Kind() == reflect.Slice {
        ...
    }
    

    I recommend you read this very helpful article: http://blog.golang.org/laws-of-reflection.

    Additionally, it will be nice to read the code of sort package: https://golang.org/pkg/sort/. It is an example of golang-way implementation of sorting.

    Edit: If you really really want use []interface{} as a parameter, actually you can do it like this:

    vs := make([]interface{}, len(list))
    for i, e := range list {
        vs[i] = e
    }
    Do(vs, f)
    

    In fact, []interface{} is not an empty interface. It's a slice type whose elements are interface{}; []int is not []interface{}, but just implements interface{}.

    I guess you want to write some kind of a general sorting method, like you write it by using generics in Java. I think it is a bad code.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计