【问题标题】:cannot use temp (type interface {}) as type []string in argument to equalStringArray: need type assertion不能在 equalStringArray 的参数中使用 temp (type interface {}) 作为 type []string:需要类型断言
【发布时间】:2014-12-02 08:13:18
【问题描述】:

我正在尝试将字符串数组传递给方法。虽然它通过了断言,但我收到了这个错误

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

代码:

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

我也试过用reflect.TypeOf(temp)检查类型,这也在打印[]string

【问题讨论】:

    标签: go


    【解决方案1】:

    你需要使用str,而不是temp

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

    【讨论】:

    • 谢谢,就是这样:)
    猜你喜欢
    • 1970-01-01
    • 2018-06-28
    • 1970-01-01
    • 2020-01-12
    • 2013-09-19
    • 1970-01-01
    • 2017-05-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多