定义

高阶函数是接收函数作为参数或返回函数作为输出的函数。

高阶函数是对其他函数进行操作的函数,要么将它们作为参数,要么返回它们。

举例

函数作为参数

package main

import "fmt"

func sum(x, y int) int {
return x + y
} func process(x int, y int, f func(int, int) int) int {
return f(x, y)
} func main() {
x, y := 1, 2
fmt.Println(process(x, y, sum))
}

输出结果

3

函数作为返回值

package main

import "fmt"

func addPrefix(str string) string {
return "prefix_" + str
} func addSuffix(str string) string {
return str + "_suffix"
} func process(idx int) func(string) string {
switch idx {
case 1:
return addPrefix
case 2:
return addSuffix
default:
return addPrefix
}
} func main() {
need_prefix := []string{"aaa", "bbb", "ccc"}
need_suffix := []string{"AAA", "BBB", "CCC"} prefix_f := process(1)
suffix_f := process(2) for i, v := range need_prefix {
need_prefix[i] = prefix_f(v)
}
for i, v := range need_suffix {
need_suffix[i] = suffix_f(v)
} fmt.Println("need_prefix:", need_prefix)
fmt.Println("need_suffix:", need_suffix)
}

输出结果

need_prefix: [prefix_aaa prefix_bbb prefix_ccc]
need_suffix: [AAA_suffix BBB_suffix CCC_suffix]

两者结合起来

衣服,交通工具,水果分类

定义一个结构体

type Commodity struct {
Name string
Type string
}
type Cds []*Commodity

自定义结构体的String()

先看一下没有自定义结构体的String(),打印出来的结果

[0xc0000ba000 0xc0000ba020 0xc0000ba040 0xc0000ba060 0xc0000ba080 0xc0000ba0a0]
map[clothes:[] fruit:[] others:[] transportation:[]]
map[clothes:[0xc0000ba080 0xc0000ba0a0] fruit:[0xc0000ba000 0xc0000ba020] others:[] transportation:[0xc0000ba040 0xc0000ba060]]
all fruit: [0xc0000ba000 0xc0000ba020]

全都是地址,所以我们需要实现自定义结构体的String()

func (cd *Commodity) String() string {
return cd.Type + "," + cd.Name
} func (cds Cds) String() string {
var result string
for _, v := range cds {
// result = append(result, v.String()...)
result += v.String() + " | "
} return result
}

再看下打印结果,顺眼多了

fruit,apple | fruit,banana | transportation,car | transportation,bike | clothes,T-shirt | clothes,skirt |
map[clothes: fruit: others: transportation:]
map[clothes:clothes,T-shirt | clothes,skirt | fruit:fruit,apple | fruit,banana | others: transportation:transportation,car | transportation,bike | ]
all fruit: fruit,apple | fruit,banana |

定一个函数,参数是用来处理每一个结构体函数,这样可以省去我们多次的for遍历

func (cds Cds) process(f func(cd *Commodity)) {
for _, v := range cds {
f(v)
}
}

正常情况下我们的输入是一串没有区分类别的数据,这种情况下我们肯定是需要去做分类的,所以我们定义个自动分类的函数

func classifier(types []string) (func(cd *Commodity), map[string]Cds) {
result := make(map[string]Cds) for _, v := range types {
result[v] = make(Cds, 0)
}
result["others"] = make(Cds, 0) appender := func(cd *Commodity) {
if _, ok := result[cd.Type]; ok {
result[cd.Type] = append(result[cd.Type], cd)
} else {
result["others"] = append(result["others"], cd)
}
} return appender, result
}

除了分类后,我们有时候可能需要在一大堆未分类的数据中找到我们需要的某一种类型,所以我们还需要定义一个查找函数

func (cds Cds) findType(f func(cd *Commodity) bool) Cds {
result := make(Cds, 0) cds.process(func(c *Commodity) {
if f(c) {
result = append(result, c)
}
})
return result
}

完整代码

package main

import "fmt"

type Commodity struct {
Name string
Type string
} type Cds []*Commodity func (cd *Commodity) String() string {
return cd.Type + "," + cd.Name
} func (cds Cds) String() string {
var result string
for _, v := range cds {
// result = append(result, v.String()...)
result += v.String() + " | "
} return result
} func main() {
fruit1 := Commodity{"apple", "fruit"}
fruit2 := Commodity{"banana", "fruit"}
transportation1 := Commodity{"car", "transportation"}
transportation2 := Commodity{"bike", "transportation"}
clothes1 := Commodity{"T-shirt", "clothes"}
clothes2 := Commodity{"skirt", "clothes"} all_commodity := Cds([]*Commodity{&fruit1, &fruit2,
&transportation1, &transportation2,
&clothes1, &clothes2}) fmt.Println(all_commodity) types := []string{"fruit", "transportation", "clothes"}
appender, cds := classifier(types)
fmt.Println(cds)
all_commodity.process(appender)
fmt.Println(cds) all_fruit := all_commodity.findType(func(cd *Commodity) bool {
return cd.Type == "fruit"
})
fmt.Println("all fruit:", all_fruit)
} func (cds Cds) process(f func(cd *Commodity)) {
for _, v := range cds {
f(v)
}
} func (cds Cds) findType(f func(cd *Commodity) bool) Cds {
result := make(Cds, 0) cds.process(func(c *Commodity) {
if f(c) {
result = append(result, c)
}
})
return result
} func classifier(types []string) (func(cd *Commodity), map[string]Cds) {
result := make(map[string]Cds) for _, v := range types {
result[v] = make(Cds, 0)
}
result["others"] = make(Cds, 0) appender := func(cd *Commodity) {
if _, ok := result[cd.Type]; ok {
result[cd.Type] = append(result[cd.Type], cd)
} else {
result["others"] = append(result["others"], cd)
}
} return appender, result
}

输出结果

fruit,apple | fruit,banana | transportation,car | transportation,bike | clothes,T-shirt | clothes,skirt |
map[clothes: fruit: others: transportation:]
map[clothes:clothes,T-shirt | clothes,skirt | fruit:fruit,apple | fruit,banana | others: transportation:transportation,car | transportation,bike | ]
all fruit: fruit,apple | fruit,banana |

Golang 高阶函数的更多相关文章

  1. c#语言-高阶函数

    介绍 如果说函数是程序中的基本模块,代码段,那高阶函数就是函数的高阶(级)版本,其基本定义如下: 函数自身接受一个或多个函数作为输入. 函数自身能输出一个函数,即函数生产函数. 满足其中一个条件就可以 ...

  2. swift 的高阶函数的使用代码

    //: Playground - noun: a place where people can play import UIKit var str = "Hello, playground& ...

  3. JavaScript高阶函数

    所谓高阶函数(higher-order function) 就是操作函数的函数,它接收一个或多个函数作为参数,并返回一个新函数. 下面的例子接收两个函数f()和g(),并返回一个新的函数用以计算f(g ...

  4. python--函数式编程 (高阶函数(map , reduce ,filter,sorted),匿名函数(lambda))

    1.1函数式编程 面向过程编程:我们通过把大段代码拆成函数,通过一层一层的函数,可以把复杂的任务分解成简单的任务,这种一步一步的分解可以称之为面向过程的程序设计.函数就是面向过程的程序设计的基本单元. ...

  5. python学习道路(day4note)(函数,形参实参位置参数匿名参数,匿名函数,高阶函数,镶嵌函数)

    1.函数 2种编程方法 关键词面向对象:华山派 --->> 类----->class面向过程:少林派 -->> 过程--->def 函数式编程:逍遥派 --> ...

  6. Scala的函数,高阶函数,隐式转换

    1.介绍 2.函数值复制给变量 3.案例 在前面的博客中,可以看到这个案例,关于函数的讲解的位置,缺省. 4.简单的匿名函数 5.将函数做为参数传递给另一个函数 6.函数作为输出值 7.类型推断 8. ...

  7. Python之路 day3 高阶函数

    #!/usr/bin/env python # -*- coding:utf-8 -*- #Author:ersa """ 变量可以指向函数,函数的参数能接收变量, 那么 ...

  8. JavaScript高阶函数 map reduce filter sort

    本文是笔者在看廖雪峰老师JavaScript教程时的个人总结 高阶函数            一个函数就接收另一个函数作为参数,这种函数就称之为高阶函数          1.高阶函数之map:   ...

  9. js高阶函数

    我是一个对js还不是很精通的选手: 关于高阶函数详细的解释 一个高阶函数需要满足的条件(任选其一即可) 1:函数可以作为参数被传递 2:函数可以作为返回值输出 吧函数作为参数传递,这代表我们可以抽离一 ...

随机推荐

  1. AOP——基于AspectJ的注解来实现AOP操作

    1.使用注解方式实现AOP操作 第一步:创建对象 <!-- 创建对象 --> <bean id="book" class="com.bjxb.aop.B ...

  2. 学习GlusterFS(九)

    环境说明: 3台机器安装 GlusterFS 组成一个集群. 使用 docker volume plugin GlusterFS 服务器: 10.6.0.140 10.6.0.192 10.6.0.1 ...

  3. C++ pair的基本用法总结

    1,pair的应用 pair是将2个数据组合成一组数据,当需要这样的需求时就可以使用pair,如stl中的map就是将key和value放在一起来保存.另一个应用是,当一个函数需要返回2个数据的时候, ...

  4. 什么是RESTFUL?REST的请求方法有哪些,有什么区别?

    这里是修真院前端小课堂,每篇分享文从 [背景介绍][知识剖析][常见问题][解决方案][编码实战][扩展思考][更多讨论][参考文献] 八个方面深度解析前端知识/技能,本篇分享的是: [什么是REST ...

  5. 前端每日实战:89# 视频演示如何用 CSS 和 D3 创作旋臂粒子动画

    效果预览 按下右侧的"点击预览"按钮可以在当前页面预览,点击链接可以全屏预览. https://codepen.io/comehope/pen/xJrOqd 可交互视频 此视频是可 ...

  6. 前端文件上传-javascript-ajax

    书写是为了更好的记忆. 方案一:form表单上传 该方案优点是支持好,缺点刷新页面. <form action="url" method="post" e ...

  7. ES6-11学习笔记--深拷贝与浅拷贝

    Object.assign,只是进行了浅拷贝,并没有进行深拷贝. 而且会在复杂结构当中会丢失属性,如下代码: let target = { a: { b: { c: 3 }, e: 4, f: 5, ...

  8. Java中if else条件判断语句的执行顺序

    学习目标: 掌握 if else 条件判断的使用 学习内容: 1.if语法 if(boolean表达式) { 语句体; } if后面的{}表示一个整体-代码块,称之为语句体,当boolean表达式为t ...

  9. web.xml 配置 contextConfigLocation

    web.xml中classpath:和classpath*:  有什么区别? classpath:只会到你的class路径中查找找文件; classpath*:不仅包含class路径,还包括jar文件 ...

  10. 前端框架小实验-在umi框架中以worker线程方式使用SQL.js的wasm

    总述:在Win7环境下配置umijs框架,在框架中用worker线程方式使用SQL.js的wasm,在浏览器端实现数据的增删改查以及数据库导出导入. 一.安装node.js 1.Win7系统只支持no ...