2.GO- variable parameter functions, anonymous functions and function variables

2.1. The variable parameter function

  • Refers to the number of variable parameters may be any parameter a
  • The variable parameters must be in the final position of the parameter list, add three dots indicate variable parameter function between the parameter name and type
  • When you declare a function in the body of the function as the variable parameters can use slices
main Package 

Import "FMT" 

FUNC Demo (String name, String hover ...) { 
	fmt.Println (name, "hobby") 

	for I, n-: = Range hover { 
		fmt.Println (I, n-) 
	} 
} 

main FUNC () { 
	Demo ( "derek", "read", "play", "game") 
} 

// results 
derek hobby is 
0 to read 
a play 
two games

2.2 anonymous function

main Package 

Import "FMT" 

FUNC main () { 
	// first: None None Return Value parameter 
	FUNC () { 
		fmt.Println ( "None None Return Value anonymous function parameter") 
	} () 

	// second: YES parameters 
	FUNC (String name) { 
		fmt.Println ( "named:", name) 
	} ( "Derek") 

	// third: the return value 
	name: FUNC = () String { 
		return "zhang_derek" 
	} () 
	FMT .Println (name) 
}

2.3. Function variables

 In the go language function is a type

  •  After Wan defined function variables, you can use an anonymous function assignment, you can use already defined function assignment
  • After defining function variables and the same general function call syntax, variable name is the function name of an ordinary function declaration
  • Function variables are referenced in addition to the fifth slice, map, channel, interface type

 (1) function is a reference type variable

main Package 

Import "FMT" 

FUNC B () { 
	fmt.Println ( "BBB") 
} 

FUNC main () { 
	// function arguments is a reference type 
	var FUNC A () 
	A = B 
	// same memory address 
	fmt.Println (a , B) // 0x47d820 0x47d820 
}

(2) function as a parameter

package main

import "fmt"

func mydo(arg func(name string))  {
	fmt.Println("执行mydo")
	arg("derek")
}

func main() {
	mydo(func(name string) {
		fmt.Println(name)
	})
}

(3) function as a return value

main Package 

Import "FMT" 

// the return value as a function 
FUNC A () FUNC () {int 
	return FUNC () {int 
		return 110 
	} 
} 

FUNC main () { 
	Result: = A () 
	R2: = Result () 
	FMT. println (R2) // 110 
}

 

Guess you like

Origin www.cnblogs.com/derek1184405959/p/11299348.html