dsewbh5588 2013-12-27 16:30
浏览 21

将字符串切片try索引方法抽象为所有切片类型

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!

  • 写回答

1条回答 默认 最新

  • doupai5450 2013-12-27 17:24
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥30 eclipse开启服务后,网页无法打开
  • ¥30 雷达辐射源信号参考模型
  • ¥15 html+css+js如何实现这样子的效果?
  • ¥15 STM32单片机自主设计
  • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢
  • ¥15 不小心不正规的开发公司导致不给我们y码,
  • ¥15 我的代码无法在vc++中运行呀,错误很多
  • ¥50 求一个win系统下运行的可自动抓取arm64架构deb安装包和其依赖包的软件。
  • ¥60 fail to initialize keyboard hotkeys through kernel.0000000000
  • ¥30 ppOCRLabel导出识别结果失败