I have this function for slices of strings:
func tryIndex(arr []string, index int, def string) string {
if index <= len(arr)-1 {
return arr[index]
}
return def
}
And I want to abstract it to a type method for slices in general.
func (i []interface) TryIndex(index int, def interface) interface {
if (index <= len(i)-1) {
return i[index]
}
return def
}
However this is giving me two errors:
prog.go:9: syntax error: unexpected ), expecting {
prog.go:13: non-declaration statement outside function body
Where line 9 is the fund declaration line and line 13 is the "return default" line.
What's going on and how can I fix it? Thanks!
Edit: one issue to my original question is also that apparently default is not allowed. I changed that to "def".
Edit: Used @WesFreeman's suggestion and resolved some issues... Now I'm getting this:
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)
Where the caller function looks roughly like this:
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")
}
Final Edit:
It's totally fine with what I had to begin with just for strings. My question mostly revolved around if it was possible to abstract it to all slice types. If not that's also a totally valid answer!
Your immediate problem is that the empty interface is interface{}
, not just interface
. So it's expecting curly braces that aren't there.
If you want to accept slices of all types, you will need to declare i
as interface{}
, not []interface{}
, since a []string
can't be assigned to a []interface{}
, but anything can be assigned to a interface{}
. Then you will need to use the reflect package to access the elements.
Your generic function will be of limited use, though, since its return value will need a type assertion to the element type of the slice. TryIndex
is basically syntactic sugar, but the type assertion will keep it from being very sweet.