英文:
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")
。
英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论