我不知道如何在不遇到几个嵌套函数问题的情况下解决这个 Go 算法问题。其中之一是,"cannot use func literal (type func()) as type func() string in return argument"。
我现在正在使用的解决方案是:
// Write a function that takes in 2 numbers (a, b) and a function.
// It should execute the function after a milliseconds,
// and then execute the function again after b milliseconds.
package main
import "time"
func newFunc(b int, fn func() string) func() string {
return func() {
time.AfterFunc(time.Duration(b)*time.Second, fn)
}
}
func solution10(a, b int, fn func() string) string {
f := newFunc(b, fn)
time.AfterFunc(time.Duration(a)*time.Second, f)
}
Run Code Online (Sandbox Code Playgroud)
我将返回类型指定solution10为字符串,因为我将传入的函数将返回字符串。也不确定这是否正确。我如何调用此解决方案的一个示例:
func yourFunc() string {
return "Hello world"
}
Run Code Online (Sandbox Code Playgroud)
solution10(10, 100, yourFunc);
Run Code Online (Sandbox Code Playgroud)
如果有人可以向我解释为什么我会收到该错误(我传入的每个函数的返回类型似乎是正确的。)或者如果有人可以提供正确的解决方案,以便我可以学习如何解决此类与闭包相关的问题的技巧?
因为time.AfterFunc需要 a func(),但你正在使用 a func() string。
如果你想调用 afunc() string你可以将它包装起来
time.AfterFunc(time.Duration(b)*time.Second, func() {
fn()
})
Run Code Online (Sandbox Code Playgroud)