Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cannot use temp (type interface {}) as type []string in argument to equalStringArray: need type assertion

Tags:

go

I'm trying to pass a string array to a method. Although it passes the assertion, I'm getting this error

cannot use temp (type interface {}) as type []string in argument to equalStringArray: need type assertion

Code:

if str, ok := temp.([]string); ok {
    if !equalStringArray(temp, someotherStringArray) {
        // do something
    } else {
        // do something else
    }
}

I've also tried checking the type with reflect.TypeOf(temp) and that's also printing []string

like image 763
Fallen Avatar asked Dec 18 '25 05:12

Fallen


1 Answers

You need to use str, not temp

see: https://play.golang.org/p/t9Aur98KS6

package main

func equalStringArray(a, b []string) bool {
    if len(a) != len(b) {
        return false
    }
    for i := 0; i < len(a); i++ {
        if a[i] != b[i] {
            return false
        }
    }
    return true
}

func main() {
    someotherStringArray := []string{"A", "B"}
    var temp interface{}
    temp = []string{"A", "B"}
    if strArray, ok := temp.([]string); ok {
        if !equalStringArray(strArray, someotherStringArray) {
            // do something 1
        } else {
            // do something else
        }
    }
}
like image 84
fabrizioM Avatar answered Dec 20 '25 03:12

fabrizioM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!