Defining and calling functions in Go language
Go language is a fast, concise and safe programming language. Its functions are first-class citizens, so in Defining and calling functions in Go language is very simple and flexible. This article will introduce how to define and call functions in the Go language, and provide specific code examples to help readers better understand.
The syntax for defining functions in Go language is very concise. The general format is as follows:
func functionName(parameter1 type1, parameter2 type2, ...) returnType { // 函数体 return returnValue }
Example: Define a simple function to calculate the sum of two integers
package main import "fmt" func add(x int, y int) int { return x + y } func main() { result := add(2, 3) fmt.Println("The sum is:", result) }
Calling function The method is also very simple, just write the function name and pass in the corresponding parameters.
Example: Call the previously defined add function
package main import "fmt" func add(x int, y int) int { return x + y } func main() { result := add(2, 3) fmt.Println("The sum is:", result) }
In addition to ordinary functions, the Go language also supports anonymous functions. That is, a function without a function name. Anonymous functions are often used in scenarios such as closures and function parameters.
Example: Define an anonymous function and assign it to a variable, then call the variable
package main import "fmt" func main() { add := func(x, y int) int { return x + y } result := add(2, 3) fmt.Println("The sum is:", result) }
In Go language, Functions can be passed as parameters to other functions, making the code more flexible and reusable.
Example: Define a function, accept a function as a parameter and call it
package main import "fmt" func apply(funcName func(int, int) int, x int, y int) int { return funcName(x, y) } func main() { add := func(x, y int) int { return x + y } result := apply(add, 2, 3) fmt.Println("The sum is:", result) }
The above is a brief introduction and example of defining and calling functions in the Go language. Through these code examples, readers can better understand how to use functions to organize code and implement functions. I hope this article will be helpful to readers who are learning the Go language.
The above is the detailed content of How to define and call functions in Go language. For more information, please follow other related articles on the PHP Chinese website!