面试题答案
一键面试创建Goroutine的常见方式
- 直接调用函数
在Go语言中,可以通过
go
关键字来创建一个新的Goroutine。例如:
package main
import (
"fmt"
)
func hello() {
fmt.Println("Hello from goroutine")
}
func main() {
go hello()
fmt.Println("Main function")
}
在上述代码中,go hello()
创建了一个新的Goroutine来执行hello
函数。主函数main
会继续执行,而不会等待hello
函数执行完毕。
- 使用匿名函数 使用匿名函数也是创建Goroutine的常见方式。例如:
package main
import (
"fmt"
)
func main() {
go func() {
fmt.Println("Hello from anonymous goroutine")
}()
fmt.Println("Main function")
}
这里使用匿名函数func() { fmt.Println("Hello from anonymous goroutine") }
创建了一个新的Goroutine。
创建时传递参数的方法
- 传递给具名函数
package main
import (
"fmt"
)
func printMessage(message string) {
fmt.Println(message)
}
func main() {
msg := "Hello, this is a parameter"
go printMessage(msg)
fmt.Println("Main function")
}
在这个例子中,msg
变量作为参数传递给printMessage
函数,在新创建的Goroutine中执行该函数时,就可以使用这个参数。
- 传递给匿名函数
package main
import (
"fmt"
)
func main() {
msg := "Hello from parameter in anonymous goroutine"
go func(m string) {
fmt.Println(m)
}(msg)
fmt.Println("Main function")
}
这里将msg
变量传递给匿名函数func(m string) { fmt.Println(m) }
,在Goroutine中匿名函数就可以使用这个参数。