dory4404 2013-11-05 22:34 采纳率: 0%
浏览 11
已采纳

链接函数如何作为goroutines执行?

Given this playground:

package main

import "fmt"

func main() {
    go oneFunc().anotherFunc()
}

func oneFunc() something {
    fmt.Println("oneFunc")
    return something{}
}

type something struct{}

func (s something) anotherFunc() {
    fmt.Println("anotherFunc")
}

Why is the output:

oneFunc

and "anotherFunc" is never printed?

  • 写回答

3条回答 默认 最新

  • dongnao9525 2013-11-05 22:42
    关注

    anotherFunc doesn't execute until oneFunc returns a value. Because of this, the program exits before anotherFunc is able to run. You need to wait for anotherFunc to run before main exits.

    You can do this via Go channels. For Example:

    http://play.golang.org/p/dWoLB9afSj

    package main
    
    import "fmt"
    
    func main() {
        ch := make(chan int)
        go oneFunc(ch).anotherFunc()
        fmt.Println("Waiting...")
        <-ch
        fmt.Println("Done.")
    }
    
    func oneFunc(ch chan int) something {
        fmt.Println("oneFunc")
        return something{ch}
    }
    
    type something struct{
        ch chan int
    }
    
    func (s something) anotherFunc() {
        fmt.Println("anotherFunc")
        s.ch <- 1
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥15 关于超局变量获取查询的问题
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集
  • ¥15 在启动roslaunch时出现如下问题
  • ¥15 汇编语言实现加减法计算器的功能
  • ¥20 关于多单片机模块化的一些问题
  • ¥30 seata使用出现报错,其他服务找不到seata