dongyanfeng0563 2012-11-12 04:11
浏览 59
已采纳

Go语言中的递归函数

I started to learn go language days ago. When I tried to start writing some fun codes, I am stuck by a strange behavior.

package main

import "fmt"

func recv(value int) {
    if value < 0 {
        return
    }

    fmt.Println(value)
    go recv(value-1)
}

func main() {
    recv(10)
}

when I run the above code, only 10 is printed. When I remove the go before the call to recv, 10 to 0 are printed out. I believe I am misusing go routine here, but I can not understand why it failed start a go routine this way.

  • 写回答

3条回答 默认 最新

  • douzhangcuo2174 2012-11-12 04:19
    关注

    When the main function returns, Go will not wait for any still existing goroutines to finish but instead just exit.

    recv will return to main after the first "iteration" and because main has nothing more to do, the program will terminate.

    One solution to this problem is to have a channel that signals that all work is done, like the following:

    package main
    
    import "fmt"
    
    func recv(value int, ch chan bool) {
        if value < 0 {
            ch <- true
            return
        }
    
        fmt.Println(value)
        go recv(value - 1, ch)
    }
    
    func main() {
        ch := make(chan bool)
        recv(10, ch)
    
        <-ch
    }
    

    Here, recv will send a single boolean before returning, and main will wait for that message on the channel.

    For the logic of the program, it does not matter what type or specific value you use. bool and true are just a straightforward example. If you want to be more efficient, using a chan struct{} instead of a chan bool will save you an additional byte, since empty structs do not use any memory.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助