What's the difference in Golang to run a function with or without go

huangapple go评论78阅读模式
英文:

What's the difference in Golang to run a function with or without go

问题

我是新手学习Go语言。我的问题是使用Go和不使用Go运行函数有什么区别。例如,在一个.go文件中,我有一个test()函数,当我调用这个函数时,"test()"和"go test()"有什么区别。

英文:

I am new to Go. My question is what's the difference to run a function with or without Go. For example in a .go file I have one test() function, when I call this function what's the difference for "test()" and "go test()".

答案1

得分: 2

test()在调用时会运行。go test()会异步地独立于test()运行。

如果你有这样一个程序:

func main() {
   test("bob")
   go test("sue")
}

func test(msg string) {
  fmt.Printf("hello %v", msg)
}

你只会看到输出:

hello bob

因为main函数的执行直接跳到了结尾。没有任何东西在等待go test("sue")完成,因为它是独立的函数。

你可以通过使用time.Sleep或者使用fmt.Scanln(&input)来阻塞go test("sue")

Go playground

英文:

test() will run when you call it. go test() will run asynchronously on its own completely independent of test().

If you have a program like this:

func main() {
   test("bob")
   go test("sue")
}

func test(msg string) {
  fmt.Printf("hello %v", msg)
}

You will only see output

> hello bob

since the main function execution jumps right through to the end. There is nothing waiting for go test("sue") to complete since it's its own independent function.

You can block for go test("sue") by putting in a time.Sleep or a command line input with fmt.Scanln(&input)

Go playground

huangapple
  • 本文由 发表于 2016年11月7日 02:37:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/40453049.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定