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

huangapple go评论76阅读模式
英文:

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

问题

我正在尝试将一个字符串数组传递给一个方法。尽管通过了断言,但我得到了以下错误:

无法将temp(类型为interface {})作为equalStringArray方法的[]string类型参数使用:需要类型断言

代码:

if str, ok := temp.([]string); ok {
    if !equalStringArray(temp, someotherStringArray) {
        // 做一些操作
    } else {
        // 做其他操作
    }
}

我还尝试使用reflect.TypeOf(temp)来检查类型,结果也打印出了[]string

英文:

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

得分: 3

你需要使用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
        }
    }
}
英文:

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 &lt; len(a); i++ {
		if a[i] != b[i] {
			return false
		}
	}
	return true
}

func main() {
	someotherStringArray := []string{&quot;A&quot;, &quot;B&quot;}
	var temp interface{}
	temp = []string{&quot;A&quot;, &quot;B&quot;}
	if strArray, ok := temp.([]string); ok {
		if !equalStringArray(strArray, someotherStringArray) {
			// do something 1
		} else {
			// do something else
		}
	}
}

huangapple
  • 本文由 发表于 2014年12月2日 16:13:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/27244663.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定