Go language function

Posted by saltwater on Mon, 24 Jan 2022 08:57:36 +0100

1, Functions

  • Functions: a block of code
  • All process control codes and business codes can only be written inside functions
  • Why use functions:
    • Put forward a function as a function, which is convenient for later maintenance and has a clear structure
  • Syntax of function declaration
    • The function will not be executed after it is declared. It must be called before it can be executed
func Function name(parameter list) Return value{
  //Function body
}

Syntax of function calls

Return value:=Function name(parameter)

2, Function with no parameter and no return value

Functions can have parameters or no parameters, return values or no return values

func main() {
	demo1()
}
func demo1(){
	fmt.Println("implement demo1 function")
}

//The above code is equivalent to
//func main(){
//	fmt.Println("execute demo1 function")
//}

3, Parametric function

  • A function can have multiple parameters, and each parameter type can be different
  • The parameter represents the value that the caller wants to pass inside the function and the value used by the function
  • The parameters when declaring a function are called shape parameters, and the parameters when calling a function are called arguments
func main() {
	i:=5
	s:="smallming"
	show(s,i)
}
func show(name string,age int){
	fmt.Println("full name:",name,"Age",age)
}

4, Function with return value

  • The return value of the function is the data returned to the caller and used by the caller
  • Function with return value must have return
func main() {
	a, b := 1, 2
	fmt.Println(add(a,b))
}
func add(c, d int) int {
	return c + d
}

You can also add a variable in front of the return value type. Nothing is written after the return keyword to indicate what the variable is and what the return value is

func main() {
	a, b := 1, 2
	fmt.Println(add2(a,b))
}

func add2(c, d int) (sum int) {
	sum = c + d
	return
}

5, Multiple return function

  • In Go language, each function can be defined as a multi return function when declared
  • All errors in the Go language are returned by return values
  • Syntax for declaring functions with multiple return values
func Function name(parameter list) (Return value,Return value){
  //Function body
}

Syntax of calling function

variable,variable:=Function name(parameter)

When calling a function, if you don't want to receive it, you can use the underscore placeholder

variable,_:=Function name(parameter)

Theoretically, the number of function return values can be unlimited, but it is generally not necessary to define a special number of return values (structure instead of multiple return values)

  • The return value of the function may not be received, indicating that the function is executed
  • If the return value of the function is received, the number of variables used to receive the return value is the same as the number of return values
  • Use placeholder () for unwanted seize a seat
func main() {
	//Do not receive function return value
	demo()

	//Each return value is received
	a, b := demo()
	fmt.Println(a, b)

	//Return values that you do not want to receive use underscore placeholders
	c, _ := demo()
	fmt.Println(c)
}

func demo() (string, int) {
	return "smallming", 17
}

Multiple return value functions can also define variables for the return value. There is no need to write content after return

func demo() (name string, age int) {
	name = "smallming"
	age = 17
	return
}

6, Variable parameter function

  • Go language supports variable parameter functions
  • Variable parameters refer to any number of parameters when calling parameters
  • The variable parameter must be at the end of the parameter list. Add three points between the parameter name and type to represent the variable parameter function
func function(parameter,parameter,name ... type ){
	//Function body
}

The output statement is a variable parameter function. The source code is as follows

func Println(a ...interface{}) (n int, err error) {
	return Fprintln(os.Stdout, a...)
}

When declaring a function, you can use variable parameters as slices in the function body

Variable parameter declaration and call

func main() {
	demo("read a book", "Write code", "Watch jiamingge video")
}

func demo(hover ... string) {
	for a, b := range hover {
		fmt.Println(a, b)
	}
}

Variable parameters must be followed by other parameters. A function cannot have multiple variable parameters

  • Because the number of ordinary parameters is determined, the compiler knows which argument is given to which formal parameter
func main() {
	demo("Zhang San", "read a book", "Write code", "Watch jiamingge video")
}

func demo(name string, hover ... string) {
	fmt.Println(name, "My hobby is")
	for a, b := range hover {
		fmt.Println(a, b)
	}
}

7, Anonymous function

  • An anonymous function is a function without a name
  • Normal functions can be called multiple times by name, while anonymous functions are declared at the current location and called immediately in most cases (except function variables) because they do not have a function name
  • After the anonymous function is declared, it needs to be called, and the closing brace of the function is followed by a parenthesis
func (){
  
}()//Parentheses indicate calls

Anonymous functions are declared inside other functions

Parameterless anonymous function

 func main(){
    func(){
       fmt.Println("This is an anonymous function")
    }()//Parentheses indicate calls
 }

Anonymous function with parameters

func main() {
   func(s string) {
      fmt.Println(s, "This is an anonymous function")
   }("Transfer parameters") //Pass parameters on call
}

Anonymous function with parameter and return value

func main() {
	r := func(s string) int {
		fmt.Println(s, "This is an anonymous function")
		return 110
	}("Transfer parameters") //Pass parameters on call
	fmt.Println(r)
}

8, Function variable

In Go language, function is also a type. As many forms of function as there are, there are as many ways to write function variables

var a func()           //No parameter no return value
var b func(int)        //There is an int type parameter
var c func(int) string //There is an int type parameter and a string type return value
fmt.Println(a, b, c)   //Output: < nil > < nil > < nil >
  • After defining function variables, anonymous functions can be used for assignment You can also use a defined function for assignment
  • After the function variable is defined, the syntax is the same as that of ordinary function calls. The variable name is the function name declared by ordinary functions
func main() {
	var a func()
	a = func() {
		fmt.Println("Execution function")
	}   //Note that there are no parentheses here. Parentheses mean to call the function, and variable a means to receive the return value of the function
	a() //Call function

	/*
	You can also use short variables to define function variables
	Equivalent to
	func b(s string){
		//...
	}
	 */
	b := func(s string) {
		fmt.Println("Execute the second function")
	}
	b("parameter")

	//Use defined functions
	d := c
	d()
	//The function name c is also a variable
	c()
}

func c() {
	fmt.Println("c function")
}

Function type variables are the fifth reference type besides slice, map, channel and interface

func main() {
	var a func()
	a = b
	a()
	var c func()
	c = a
	c()
	fmt.Printf("%p %p", a, c)//Same output address
}

func b() {
	fmt.Println("b")
}

9, Function as an argument or return value

  • Variables can be used as parameters or return value types of functions Since functions can be treated as variables, function variables can also be treated as parameters or return values of functions
  • When a function is used as a parameter, the type can be written as the corresponding type
func main() {
	a(func(s string) {
		fmt.Println(s)
	})
}

func a(b func(s string)) {
	fmt.Println("a implement")
	b("Pass to s Content of")
}

Function as return value

func main() {
	//At this point, result points to the return value function
	result := a()
	//Call the function to get the result
	fmt.Println(result())
}

func a() func() int {
	return func() int {
		return 110
	}
}

Topics: Go