简体   繁体   中英

How to make a function accept any type array as param in GO?

I need to create a function that takes any type array as param.

package main

import "fmt"

type flt func(interface{}) bool

func filter(sl []interface{}, f flt) (filtered []interface{}) {
    // todo call flt to each element on array
    return
}

func f1(interface{}) bool{
    return true
}

func main() {
    slice := []int{1, 2, 3, 4, 5, 7}
    filter(slice, f1)
}
./prog.go:16:8: cannot use slice (type []int) as type []interface {} in argument to filter

I founded this question , but the solution doesn't work with arrays.

edit1. By the way, you probably notice, but I'm trying to create a "map function" to any array, just like JS array.filter()

I was wrong about the use of Interface{}. I don't need to say that it's an array, just a regular Interface{} is able to receive a slice of any type.

Just like icza said I used reflection to get the type of Interface{}, but by using "reflect.TypeOf(el).Kind().= reflect. Slice" I avoided the manual type handler and get my general function just like I wanted.

package main

import (
    "errors"
    "reflect"
)

type flt func(interface{}) bool

func filter(el interface{}, f flt) (filtered interface{}, err error) {
    if reflect.TypeOf(el).Kind() != reflect.Slice {
        err = errors.New("Passed element is not an slice")
        filtered = el
        return
    }
    // todo -> apply flt to each element from array
    return
}

func f1(interface{}) bool {
    return true
}

func main() {
    slice := []int{1, 2, 3, 4, 5, 7}
    slice2 := []string{"1", "2", "a"}
    filter(slice, f1)
    filter(slice2, f1)
    filter(1, f1)
}

check this also: How to check if interface{} is a slice

You can still use reflect

package main

import (
    "fmt"
    "reflect"
)

type flt func(interface{}) bool

func filter(sl interface{}, f flt) interface{} {
    v := reflect.ValueOf(sl)
    filtered := reflect.MakeSlice(v.Type(), 0, v.Len()-1)
    for i := 0; i < v.Len(); i++ {
        if f(v.Interface()) {
            filtered = reflect.Append(filtered, v.Index(i))
        }
    }

    return filtered.Interface()
}

func f1(interface{}) bool {
    return true
}

func main() {
    slice := []int{1, 2, 3, 4, 5, 7}
    filtered := filter(slice, f1)
    for _, v := range filtered.([]int) {
        fmt.Printf("Filtered value: %v\n", v)
    }
}

https://go.dev/play/p/hmzgUD8ceb1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM