Reputation: 644
I can't figure out how to solve this Go algorithm problem without running into a couple nested function problems. One of them being, "cannot use func literal (type func()) as type func() string in return argument"
.
The solution I'm working with right now is:
// 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)
}
I specified the return type of solution10
as string because the function I'll be passing in will be returning a string. Not sure if this is right either. An example of how I would call this solution:
func yourFunc() string {
return "Hello world"
}
solution10(10, 100, yourFunc);
I'd love if someone can explain to me why I am getting that error (the return types of each function I'm passing in seem to be right.) Or if someone could just please offer a right solution for it so that I could learn tricks in how to solve these type of closure-related questions?
Upvotes: 0
Views: 3268
Reputation: 3424
Because time.AfterFunc
takes a func()
, but you are using a func() string
.
if you want to call a func() string
you could wrap it
time.AfterFunc(time.Duration(b)*time.Second, func() {
fn()
})
Upvotes: 5