what is go func()
时间: 2023-10-05 07:07:22 浏览: 95
golang善用go func和defer
In Go language, `func()` is a keyword used to define a function. It is used to declare a function literal, also known as an anonymous function. An anonymous function is a function without a name that can be defined inline with other code.
The `go` keyword is used to start a new goroutine, which is a lightweight thread of execution. When a goroutine is started with `go func()`, the function is executed concurrently with the calling function. The `func()` is a function literal that defines the code to be executed in the new goroutine.
Here's an example of using `go func()` to start a new goroutine:
```
func main() {
go func() {
fmt.Println("Hello from a goroutine!")
}()
fmt.Println("Hello from main!")
}
```
In this example, the `go func()` starts a new goroutine that prints "Hello from a goroutine!" while the main function prints "Hello from main!". The output may vary on each execution, as the two goroutines run concurrently.
阅读全文