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)
}
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>
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.
The errors are telling you that you are trying to pass an int array (the slice
variable) to the function Do
, which is expecting it's first argument as type SortList
.
Also, your interface definition does not look right. You have array syntax in there. It should look like this:
type SortList interface{}
I suggest you take a look at the gobyexample page on interfaces.