Go Language function value transfer and closure

Source: Internet
Author: User
Tags closure hypot pow
Function Value Pass
A function is also a value. They can be passed like other values, for example, the function value can be used as a function parameter or a return value.
Package main

Import (
	"FMT"
	"math"
)

func Compute (fn func (float64, float64) float64) float64 { Return
	FN (3, 4)
}

Func Main () {
	Hypot: = Func (x, y float64) float64 {return
		math. SQRT (x*x + y*y)
	}
	fmt. Println (Hypot (5))   //Call hypot function, output

	FMT. Println (Hypot)  //Compute the Hypot function as a parameter to the COMPUTE function, using 3,4 as a parameter call to the Hypot function, the result is 5
	FMT. PRINTLN (COMPUTE) (math. Pow))  //Will math. The POW function acts as an argument to the compute function, using 3,4 as the calling math. Pow function parameter call, the result is Bayi
}

Closure of functions
Package main

Import "FMT"
func adder (i int) func (int) int {
	sum: = I return
	func (x int) int {
		sum = x return
		sum
	}
}

Func adder2 (i int) func () int {
	sum: = I return
	func () int {return
		sum
	}
}

func main () {
  fmt. Printf ("%t\n", Adder2 (3))  //The type returned here is a function func () int
	FMT. Println (Adder2 (3) ())       //Use this method to return to the final result 3
	
	pos, neg: = Adder (1), adder (1) for
	I: = 0; i < 3; i++ {
		FMT.P Rintln (
			pos (i),
			neg ( -2*i),             //This is also the way the closure function is invoked, resulting in 1 1,2-1,4-5
		)
	}




Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.