A function is a basic code block that is used to perform a task.
The Go language has at least one main()
function.
You can divide code by functions, and logically each function performs a specified task.
The function declaration tells the name of the compiler function, the return type, and the parameters.
Syntax
The function definition Go language function definition is in the following format:
func function_name( [parameter list] ) [return_types]{
}
Function definition resolution:
func
: Function starts declaring function_name by funcfunction name
: function name, and parameter list together form function signature.-
parameter list
: The parameter list, the parameter is like a placeholder, and when the function is called, you can pass the value(s) as parameter(s).The parameter list specifies the parameter type, order, and number of arguments. The parameters are optional, that is, the function can also not contain arguments.
return_types
: Return type, function returns a column value. Some features do not require a return value, such that return_types are not required.Function body
: A collection of codes defined by the function. The body is between the{
and}
symbols.
Examples
The following instance is the code of the max()
function that passes in two integer arguments num1
and num2
, and returns the maximum value of these two parameters:
/* function returns maximum value */
func max(num1, num2 int) int{
result int
if (num1 > num2) {
result = num1
} else {
result = num2
}
return result
}
When a function call creates a function, you define what the function needs to do and perform the specified task by calling the change function.
Call a function, pass arguments to the function, and return a value, such as:
package main
import "fmt"
func main() {
var a int = 100
var b int = 200
var ret int
ret = max(a, b)
fmt.Printf( "Returns : %d\n", ret )
}
func max(num1, num2 int) int {
var result int
if (num1 > num2) {
result = num1
} else {
result = num2
}
return result
}
Reference:
Top comments (0)