3

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

1 Answer 1

3

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
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.