Golang function as type

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.
Golang function as type package Mainimport"FMT"type A func (int,int) func (f A) Serve () {fmt. Println ("Serve2")}func serve (int,int) {fmt. Println ("serve1")}func Main () {a:=A (serve) a (1,2) A.serve ()}

Type Functintyoe func (int)BOOL //declares a function typefunc isodd (integerint)BOOL {    ifinteger%2==0 {        return false    }    return true} func isEven (integerint)BOOL {    ifinteger%2==0 {        return true    }    return false} //declared function type in this place as a parameterfunc filter (slice []int, f Functintyoe) []int {    varresult []int     for_, Value: =Range Slice {iff (value) {result=Append (result, value)}} returnresult} func Test () {slice:= []int{1,2,3,4,5,7} fmt. Println ("slice =", slice) odd:= Filter (slice, isodd)//function as a value to pass theFmt. Println ("Odd elements of slice are:", Odd) even:= Filter (slice, IsEven)//function as a value to pass theFmt. Println ("even elements of slice are:", even)} 

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.