开始文章之前我们要先弄清楚什么是『泛型编程』。

In the simplest definition, generic programming is a style of computer programming in which algorithm are written in terms of types to-be-specified-later that are then instantiated when needed for specific types provided as parameters. – From Wikipedia.

简单来说就说,我们编写的代码不是针对特定的类型(比如适用于int, 不适用于string)才有效,而是大部分类型的参数都是可以工作的。

我们来看一个C++的例子:1

2

3

4

5

6

7

8

9

10#include

#include

int main(){

std::vector A{3,1,2,4,5};

std::vector B{"golang", "I", "am"};

std::sort(A.begin(), A.end());//after this, A={1,2,3,4,5}

std::sort(B.begin(), B.end());//after this, B={"I", "am", "golang"}

return 0;

}

这里的sort函数就是一个泛型编程例子。至于为什么{“golang”, “I”, “am”}排序之后变成{“I”, “am”, “golang”}是因为string类型的比较函数是字典序。细心的人可能会注意到这儿直接使用大括号来初始化vector,是的,这是C++11。

Go有泛型编程吗?

没有。

为什么Go没有泛型编程?

这里应用官网的回答

Why does Go not have generic types?

Generics may well be added at some point. We don’t feel an urgency for them.Generics are convenient but they come at a cost in complexity in the type system and run-time…

Meanwhile, Go’s built-in maps and slices, plus the ability to use the empty interface to construct containers mean in many cases it is possible to write code that does what generics would enable, if less smoothly.

翻译一下,就是尽管泛型很好,但是它会让我们的语言设计复杂度提升,所以我们现在暂时不打算支持,以后可能会支持。另外,虽然我们现在很弱,但是使用Interface也是可以实现泛型了(呵呵)。

Go的泛型编程实现

前面说了使用Go的interface可以实现泛型编程,那么我们先理解一下interface。

duck typing

这里引入一个概念,duck typing。

When I see a bird that walks like a duck and swins like a duck and quacks like a duck, I call that bird a duck. – James Whitcomb Riley

结合维基百科的定义,duck typing是面向对象编程语言的一种类型定义方法。我们判断一个对象是神马不是通过它的类型定义来判断,而是判断它是否满足某些特定的方法和属性定义。

interface

那么Go中interface是什么呢?interface是一组方法集合。我们可以把它看成一种定义内部方法的动态数据类型,任意实现了这些方法的数据类型都可以认为是特定的数据类型。

泛型编程

其实Go语言中也提供了sort函数,我们看一下源码,src/sort/sort.go。1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30package sort

// A type, typically a collection, that satisfies sort.Interface can be

// sorted by the routines in this package. The methods require that the

// elements of the collection be enumerated by an integer index.

type Interface interface {

// Len is the number of elements in the collection.

Len() int

// Less reports whether the element with

// index i should sort before the element with index j.

Less(i, j int) bool

// Swap swaps the elements with indexes i and j.

Swap(i, j int)

}

...

// Sort sorts data.

// It makes one call to data.Len to determine n, and O(n*log(n)) calls to

// data.Less and data.Swap. The sort is not guaranteed to be stable.

func Sort(data Interface) {

// Switch to heapsort if depth of 2*ceil(lg(n+1)) is reached.

n := data.Len()

maxDepth := 0

for i := n; i > 0; i >>= 1 {

maxDepth++

}

maxDepth *= 2

quickSort(data, 0, n, maxDepth)

}

其中省略了一些源码,我们看到package中定义了一个Interface,包含三个方法:Len(), Less(), Swap()。Interface作为参数传递给Sort。我们要使用Sort,只需要实现Interface的三个方法就可以使用下面是一个例子。1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36package main

import (

"fmt"

"sort"

)

type Person struct {

Name string

Age int

}

func (p Person) String() string {

return fmt.Sprintf("%s: %d", p.Name, p.Age)

}

// ByAge implements sort.Interface for []Person based on

// the Age field.

type ByAge []Person

func (a ByAge) Len() int { return len(a) }

func (a ByAge) Swap(i, j int) { a[i], a[j] = a[j], a[i] }

func (a ByAge) Less(i, j int) bool { return a[i].Age < a[j].Age }

func main() {

people := []Person{

{"Bob", 31},

{"John", 42},

{"Michael", 17},

{"Jenny", 26},

}

fmt.Println(people)

sort.Sort(ByAge(people))

fmt.Println(people)

}

有疑问加站长微信联系(非本文作者)

php 泛型编程,go泛型编程相关推荐

  1. 原来C语言还可以这样实现“泛型编程”!

    在回答标题问题之前,先了解下什么是泛型编程. 泛型编程(generic programming)是程序设计语言的一种风格或范式.泛型允许程序员在强类型程序设计语言中编写代码时使用一些以后才指定的类型, ...

  2. C++ 泛型编程的基础--模板初识及应用

    了解模板之前我们要先知道什么是泛型编程:泛型编程的代表作品STL是一种高效.泛型.可交互操作的软件组件.STL以迭代器 (Iterators)和容器(Containers)为基础,是一种泛型算法(Ge ...

  3. c 是泛型程序设计语言,在C语言中实现泛型编程

    0x00 泛型编程概述 泛型编程是一个非常常见的编程方式.主要目的是实现静态联编,使得函数可以接受不同类型的参数,并且在编译的时候确定正确的类型. 很多语言都对泛型编程提供了支持,比如在C++中可以使 ...

  4. 泛型编程、STL的概念、STL模板思想及其六大组件的关系,以及泛型编程(GP)、STL、面向对象编程(OOP)、C++之间的关系

    介绍STL模板的书,有两本比较经典: 一本是<Generic Programming and the STL>,中文翻译为<泛型编程与STL>,这本书由STL开发者 Matth ...

  5. c++ Factor泛型编程示例

    c++ Factor泛型编程示例 c++ 泛型编程 之Factor (c++ 设计新思维) 一.概述 泛化仿函数是将"请求(函数)封装起来",存储与对象中,该对象是具有" ...

  6. C++ 泛型编程 -- 函数模版

    文章目录 定义 声明 调用方式 函数模版的重载 函数模版的特点 工作中一个同事写了测试demo,想要自己尝试使用发现调用老出错,请教的时候发现是函数模版,有自己的调用方式,并且发现核心代码中大量的函数 ...

  7. C++泛型编程:template模板

    泛型编程就是以独立于任何特定类型的方式编写代码,而模板是C++泛型编程的基础. 所谓template,是针对"一个或多个尚未明确的类型"所编写的函数或类. 使用template时, ...

  8. C语言如何实现泛型编程?

    泛型编程让你编写完全一般化并可重复使用的算法,其效率与针对某特定数据类型而设计的算法相同.在 C 语言中,可以通过一些手段实现这样的泛型编程. 这里介绍一种方法--通过无类型指针 void*. 看下面 ...

  9. C++_泛型编程与标准库(十)——set与map

    C++_泛型编程与标准库(十)--set与map 参考:<侯捷泛化编程与标准库>.GNU9.3.0,vs2019 图中标红部分为自己的笔记理解 SET GNU 9.3.0的set部分代码如 ...

最新文章

  1. 程序员面试题100题第19题——反转链表
  2. rxjs里使用from operator从一个generator里生成Observable
  3. 高中计算机编辑程序,高中信息技术信息的编程加工教案
  4. 实践SaltStack安装和配置管理
  5. Java空指针异常:java.lang.NullPointException
  6. java http服务_springboot官方例子中文翻译--RESTful服务启用CORS支持
  7. php短网址案例,php 短网址小例子
  8. matlab编写LDA,lda算法matlab实现
  9. Java语言学习指导与习题解答_Java语言程序设计(第3版)学习指导与习题解析
  10. gms2游戏移植linux,GMS卡刷包制作
  11. 谈嵌入式软件分层设计
  12. 大浪淘沙-新浪发展的秘密
  13. 竞业限制了不能做任何行业的相关联岗位,合理吗?
  14. ios搜索(可实现模糊搜索 支持拼音检索 首字母等)
  15. 2021-04-17
  16. C#读取RFID卡号源码
  17. PHP获取Opcode及C源码
  18. 徐东山:腾讯云安全的使命和技术实现
  19. 一文弄懂Batch Norm / Layer Norm / Instance Norm / Group Norm 归一化方法
  20. Uniapp之API promise化

热门文章

  1. elasticsearch kibana简单查询
  2. 计算机上n,在n上的另一台计算机上启动进程
  3. nubia ui 5.0 android,国内首家 基于安卓5.0开发nubia UI公测
  4. 闲鱼高效投放背后的秘密——鲲鹏
  5. Python中将True/False转为1/0的方法
  6. 计算机二级成绩划分标准,计算机二级成绩查询2021 计算机二级成绩划分标准
  7. java基础——求数组长度、遍历数组、求最值和数组元素反转
  8. 什么是云原生分布式数据库?
  9. python读取tiff文件_python+tifffile之tiff文件读写方式
  10. 好久不见了,天堂之上,愿你安好