Fallen
Fallen

Reputation: 4565

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

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

Upvotes: 3

Views: 2533

Answers (1)

fabmilo
fabmilo

Reputation: 48330

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

Upvotes: 3

Related Questions