【发布时间】:2014-01-15 05:58:52
【问题描述】:
我有这个用于字符串切片的函数:
func tryIndex(arr []string, index int, def string) string {
if index <= len(arr)-1 {
return arr[index]
}
return def
}
我想将其抽象为一般切片的类型方法。
func (i []interface) TryIndex(index int, def interface) interface {
if (index <= len(i)-1) {
return i[index]
}
return def
}
但是这给了我两个错误:
prog.go:9: syntax error: unexpected ), expecting {
prog.go:13: non-declaration statement outside function body
其中第 9 行是基金申报行,第 13 行是“回报默认”行。
发生了什么,我该如何解决?谢谢!
编辑:我原来的问题的一个问题是显然不允许默认值。我把它改成了“def”。
编辑:使用@WesFreeman 的建议并解决了一些问题......现在我明白了:
prog.go:16: invalid receiver type []interface {} ([]interface {} is an unnamed type)
prog.go:27: aArr.TryIndex undefined (type []string has no field or method TryIndex)
prog.go:28: bArr.TryIndex undefined (type []string has no field or method TryIndex)
调用者函数大致如下:
aArr := []string{"al", "ba", "ca"} // Arbitrary variable
bArr := []string{"tl", "cl", "rl"} // same
for i := range aArr {
aR := aArr.TryIndex(i, "00")
bR := bArr.TryIndex(i, "00")
}
最终编辑:
我刚开始的字符串完全没问题。我的问题主要围绕是否可以将其抽象为所有切片类型。如果不是,那也是一个完全有效的答案!
【问题讨论】:
-
default是保留关键字,不能用作标识符:Keywords。