gpt4 book ai didi

go - 使用闭包在 Go 中编写下一个排列,我的代码有什么问题

转载 作者:数据小太阳 更新时间:2023-10-29 03:36:41 25 4
gpt4 key购买 nike

我编写了一个使用闭包的函数“iterPermutation”。我想从我做不到的闭包中返回数组和 bool 值。所以只尝试了数组,但它仍然报错

cannot use func literal (type func() []int) as type []int in return argument

我想像这样使用 iterPermutation

a := []int{0,1,2,3,4}
nextPermutation, exists := iterPermutation(a)
for exists {
nextPermutation()
}

func iterPermutation(a []int) []int {
return func() []int {
i := len(a) - 2

for i >= 0 && a[i+1] <= a[i] {
i--
}
if i < 0 {
return a
}

j := len(a) - 1
for j >= 0 && a[j] <= a[i] {
j--
}

a[i], a[j] = a[j], a[i]

for k, l := i, len(a)-1; k < l; k, l = k+1, l-1 {
a[k], a[l] = a[l], a[k]
}
return a
}
}

最佳答案

Return statements 的 Golang 规范描述:

The return value or values may be explicitly listed in the "return" statement. Each expression must be single-valued and assignable to the corresponding element of the function's result type.

用于置换的函数应包含两个返回值,一个用于数组,另一个用于 bool 值。由于您要从函数返回中分配两个变量:

a := []int{0,1,2,3,4}
nextPermutation, exists := iterPermutation(a) // it should return two values one for nextPermutation which is an array and other is exists which might be a boolean value.
for exists {
nextPermutation()
}

对于以下错误:

"cannot use func literal (type func() []int) as type []int in return argument"

你返回的 func() 文字包含在置换的闭包函数中以及 bool 值,因此将返回类型更改为:

package main

func main(){
a := []int{0,1,2,3,4}
nextPermutation, _ := iterPermutation(a)
nextPermutation()
}

func iterPermutation(a []int) ((func() []int), bool) { // return both values
return func() []int {
i := len(a) - 2

for i >= 0 && a[i+1] <= a[i] {
i--
}
if i < 0 {
return a
}

j := len(a) - 1
for j >= 0 && a[j] <= a[i] {
j--
}

a[i], a[j] = a[j], a[i]

for k, l := i, len(a)-1; k < l; k, l = k+1, l-1 {
a[k], a[l] = a[l], a[k]
}
return a
}, true // add boolean value to return from the function.
}

关于 Playground 的工作答案

关于go - 使用闭包在 Go 中编写下一个排列,我的代码有什么问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52166062/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com