写一个函数。这是一个示例,假设IndexOf返回数字的第一个索引,如果没有找到则返回 -1。// IndexOf returns the first index of needle in haystack// or -1 if needle is not in haystack.func IndexOf(haystack []int, needle int) int { for i, v := range haystack { if v == needle { return i } } return -1}在 Go Programming Language Playground 上运行此代码。
在 go 中没有通用的库函数可以为您执行此操作。但是,如果您使用的是字节切片,则可以使用IndexByte(b []byte, c byte) int。或者您可以编写一个快速函数来为您执行此操作:func indexOf(arr []int, val int) int { for pos, v := range arr { if v == val { return pos } } return -1}