如何找出切片中的元素位置? [英] How to find out element position in slice?
本文介绍了如何找出切片中的元素位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要如下所示的内容:
类型intSlice [] int
func(slice intSlice)pos(value int)int {
for p,v:
if(v == value){
return p
}
}
return -1
}
解决方案
对不起,没有通用库函数来执行此操作。 Go没有直接写一个可以在任何分片上运行的函数。
你的函数可以工作,但是如果你写它的话会更好一些使用 range
。
如果你碰巧有一个字节片段,那么 bytes.IndexByte 。
How does one determine the position of an element present in slice?
I need something like the following:
type intSlice []int
func (slice intSlice) pos(value int) int {
for p, v := range slice {
if (v == value) {
return p
}
}
return -1
}
解决方案
Sorry, there's no generic library function to do this. Go doesn't have a straight forward way of writing a function that can operate on any slice.
Your function works, although it would be a little better if you wrote it using range
.
If you happen to have a byte slice, there is bytes.IndexByte.
这篇关于如何找出切片中的元素位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文