duangan6797 2019-01-08 00:36
浏览 281

无法在参数time.AfterFunc中使用func()类型的函数

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?

  • 写回答

1条回答 默认 最新

  • dtuy84033 2019-01-08 00:46
    关注

    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()
    })
    
    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看