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 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数