function as variable, type---Golang

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

The function in Go is also a variable, and we define the type of the variable by type. Functions that have the same parameters and the same return value belong to the same type.


By using a function as a variable of one type, we can pass this type of function as a value.

The following is a simple example.


Type functintyoe func (int) bool//declares a function type func isodd (integer int) bool {if integer%2 = = 0 {return False}return true}func IsEven (integer int) bool {if integer%2 = = 0 {return True}return false}//declared function type in this place as a parameter func filter (slice []int, F Fu Nctintyoe) []int {var result []intfor _, Value: = Range Slice {if f (value) {result = Append (result, value)}}return result} Func Test () {    slice: = []int {1, 2, 3, 4, 5, 7}    FMT. Println ("slice =", slice)    odd: = Filter (slice, isodd)    //function as a value to pass the    FMT. Println ("Odd Elements of Slice is:", ODD)    even: = Filter (slice, IsEven)  //function as a value to pass the    FMT. Println ("Even elements of Slice is:", even)}


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.