Function is the encapsulation of a piece of code, especially the code that needs to be repeatedly called, encapsulated in the function, which not only avoids repeated writing, but also makes the code structure clearer and concise.

1. Function definition

The keyword func is used to define functions in Go. Here are four types of function definitions:

(1) A function with no arguments and no return value

func f1(a){
		fmt.Println("f1")}Copy the code

(2) There is no return value for a parameter

func f2(x int,y int){
		fmt.Println(x,y)
	}
Copy the code

(3) No parameter has a return value

func f3(a) int{
		return 100
	}
Copy the code

(4) There are parameters and return values

func f4(x int,y int) int{
		return x+y
	}
Copy the code

Function definition Considerations:

  • You can name the return value in the return value of the function header.

    The named return value is equivalent to declaring a variable in the function in advance.

    Return doesn’t have to be return ret.

	func f5(x int,y int)ret int){
		ret = x+y
		return 
	}
Copy the code
  • Go supports multiple return values

    Multiple return values make it easy to obtain multiple return parameters of a function after execution. Go often uses the last return parameter of multiple return values to return errors that may occur during the execution of a function.

C/C + + language support only a return value, when need to return multiple values, the need to use the structure returned as a result, or the use of pointer variable parameter, and then modify the variable values of the incoming outside inside the function implementation returns results, in C + + language for the sake of safety, recommendations in the parameter return a pointer to data with a “reference” alternative.

  • Define variable length parameters

    Variable length arguments must be placed at the end of function arguments

// Variable length argument
/ / add after y... Indicates that multiple parameters can be added
func f6 (x string, y...int) {
	fmt.Println(x)
	fmt.Println(y)  //y is a slice of int type
}

func main(a){
	f6("Mice love rice.".1.23.4.6)}Copy the code

Output result:

Mice love rice [1 23 4 6]Copy the code
  • There is no default parameter in Go language, which is different from C/C ++/ Python. In Go, there are only two kinds of parameters: pass or not pass. This is the design mechanism of Go, which helps to unify the code.