go"泛型程式設計"

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

開始文章之前我們要先弄清楚什麼是『泛型程式設計』。

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 <algorithm>
#include <vector>

int main() {
std::vector<int> A{3,1,2,4,5};
std::vector<string> 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
30
package 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
36
package 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)
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.