【问题标题】:Is golang []interface{} cannot be function parameter? [duplicate]golang []interface{} 不能作为函数参数吗? [复制]
【发布时间】:2015-12-24 18:34:21
【问题描述】:

我的代码:


package sort_test

type SortList []interface{}

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


func Do(list SortList, function SortFunc)

主包


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

编译错误

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

【问题讨论】:

    标签: algorithm go interface


    【解决方案1】:

    不能。接口就是接口。

    interface{} 不是某种“任何”类型。 但是,任何类型都实现了 interface{}。接口只是一组应该实现的方法。

    如果要检查interface{}是否为slice,可以这样写:

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

    我建议您阅读这篇非常有用的文章:http://blog.golang.org/laws-of-reflection

    另外,阅读排序包的代码会很高兴:https://golang.org/pkg/sort/。这是一个golang方式实现排序的例子。

    编辑:如果你真的想使用 []interface{} 作为参数,实际上你可以这样做:

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

    其实 []interface{} 并不是一个空接口。它是一个切片类型,其元素是 interface{}; []int 不是 []interface{},只是实现了 interface{}。

    我猜你想写一些通用的排序方法,就像你在 Java 中使用泛型一样。我认为这是一个糟糕的代码。

    【讨论】:

    • 谢谢!之前的“接口”我不是很懂
    【解决方案2】:

    错误告诉您,您正在尝试将一个 int 数组(slice 变量)传递给函数 Do,该函数期望它的第一个参数为 SortList 类型。

    另外,您的接口定义看起来不正确。你在那里有数组语法。它应该是这样的:

    type SortList interface{}
    

    我建议你看看接口上的gobyexample 页面。

    【讨论】:

    • type SortList []interface{}
    • []interface{}不能作为函数参数?
    猜你喜欢
    • 2016-03-03
    • 2020-02-13
    • 2018-10-26
    • 2013-09-19
    • 1970-01-01
    • 2020-07-03
    • 2014-02-15
    • 1970-01-01
    • 2017-01-18
    相关资源
    最近更新 更多