【问题标题】:Is there any function in golang that will find the value is in array or not?golang中是否有任何函数可以找到值是否在数组中?
【发布时间】:2019-03-28 15:46:54
【问题描述】:

假设有一个切片,其中包含整数。我们已经声明了一个包含整数值的变量,然后我必须在不使用 for 循环的情况下从该切片中找到值。

使用 for 循环我喜欢这样:-

package main

import (
   "fmt"
)

func main() {
  value := 10
  var interf []interface{}
  for i := 1; i <= value; i++{
    interf = append(interf, i)
  } 
  fmt.Println(interf)
  for _,v := range interf{
    if value == v{
       fmt.Println("Matched")
    }
  }
}

我们如何在不使用 for 循环的情况下做同样的事情

【问题讨论】:

  • 那里,golang 对此没有办法。你可以阅读更多here
  • @MaxianNicu play.golang.org/p/PGx3gRSgjMx 这是一个游乐场,请告诉我如何在我的代码中实现它
  • 无论如何,for 循环是不可避免的。您至少需要查看切片中的值一次以判断它是否存在,这需要一个循环或复杂度类似的东西(即 O(n) )。如果您认为它看起来很重复或无聊,您可以将其抽象为一个函数。

标签: arrays loops go slice


【解决方案1】:

没有for 循环,就没有*(参见How to search for an element in a golang slice),但是......你对for 循环有什么看法?为什么你不能为此使用循环?这个问题就像“我可以不用编码就能做到吗”

* 实际上,您可以在没有for 循环的情况下使用递归函数来做到这一点,但这仅对教育目的有用,对实际目的毫无价值。请参阅答案末尾的解决方案。

标准库中没有现成的函数,但是自己创建一个是多么容易:

func find(what interface{}, where []interface{}) (idx int) {
    for i, v := range where {
        if v == what {
            return i
        }
    }
    return -1
}

并使用它:

what := 10
where := []interface{}{1, 2, 3, 10, 5}
fmt.Println(find(what, where))

输出(在Go Playground上试试):

3

还要注意使用[]int切片类型而不是[]interface{}会更快更方便:

func find(what int, where []int) (idx int) {
    for i, v := range where {
        if v == what {
            return i
        }
    }
    return -1
}

然后使用它:

what := 10
where := []int{1, 2, 3, 10, 5}
fmt.Println(find(what, where))

输出是一样的。在Go Playground 上试试这个。

您可以使用interface{} 类型创建一个接受任何类型切片的函数,但这需要反射来实现它,这会更慢且不值得使用。如果需要,只需创建一个具有具体切片类型的函数,或者直接使用 for 循环。

为了完整起见,这里的解决方案不使用for 循环,而是使用递归函数。这仅用于教育目的,上述解决方案优于此:

func find(what int, where []int) (idx int) {
    if len(where) == 0 {
        return -1
    }
    if what == where[0] {
        return 0
    }
    if idx = find(what, where[1:]); idx < 0 {
        return -1 // Not found in the rest of the slice
    }
    return 1 + idx
}

Go Playground 上试试这个。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-17
    • 2023-03-31
    • 2013-12-07
    • 2017-10-09
    • 2021-11-16
    • 1970-01-01
    • 2018-01-31
    相关资源
    最近更新 更多