amtoaer

晓风残月

叹息似的渺茫,你仍要保存着那真!
github
x
telegram
steam
nintendo switch
email

前往泛型初探

Go 團隊於 12 月 14 日發布了 Go 1.18 Beta 1,正式引入了對泛型的支援。詳見 The Go Blog。筆者近日也下載嘗了個鮮。

下載安裝#

按照官方文件下載安裝 beta 版本:

❯ go install golang.org/dl/go1.18beta1@latest

# 注:以下可執行檔位於$GOPATH/bin,如未配置環境變數可手動指定路徑
❯ go1.18beta1 download 

❯ go1.18beta1 version
go version go1.18beta1 linux/amd64

安裝完成!

簡單體驗#

參考官方的泛型文件,我們可以輕鬆寫出一個累加任意可加 slice 的方法:

image-20211224190117034

由於 Go 的工具鏈還未更新適配新語法,vscode 會提示語法錯誤,不過實際運行的輸出結果符合預期。

深入理解#

想必很多人都想進一步了解 Go 新泛型的語法和用法,可遺憾的是官方似乎只給出了上節提到的簡單文件,沒有更詳盡的解釋了。目前我只找到了一些第三方的泛型示例,感興趣的可以閱讀代碼加深理解。

個人感想#

或許是因為文件的欠缺,單單看示例讓我很難想像到泛型的實際用處。本來拿到泛型後最想嘗試的是實現多類型 slice 的排序,即批量實現sort.Interface

type Interface interface {
	// Len is the number of elements in the collection.
	Len() int

	// Less reports whether the element with index i
	// must sort before the element with index j.
	//
	// If both Less(i, j) and Less(j, i) are false,
	// then the elements at index i and j are considered equal.
	// Sort may place equal elements in any order in the final result,
	// while Stable preserves the original input order of equal elements.
	//
	// Less must describe a transitive ordering:
	//  - if both Less(i, j) and Less(j, k) are true, then Less(i, k) must be true as well.
	//  - if both Less(i, j) and Less(j, k) are false, then Less(i, k) must be false as well.
	//
	// Note that floating-point comparison (the < operator on float32 or float64 values)
	// is not a transitive ordering when not-a-number (NaN) values are involved.
	// See Float64Slice.Less for a correct implementation for floating-point values.
	Less(i, j int) bool

	// Swap swaps the elements with indexes i and j.
	Swap(i, j int)
}

寫了老半天也沒能成功,就放棄了... 如果有讀者了解的話,還望在評論區不吝賜教。

希望能儘快看到 Go 官方的詳細泛型文件吧!

載入中......
此文章數據所有權由區塊鏈加密技術和智能合約保障僅歸創作者所有。