Go1.18 泛型約束語法變更,可通過新 playground 驗證
Go1.18 功能已經(jīng)完全確認(rèn),代碼已經(jīng)凍結(jié),目前還有 100+ issue 要處理。

今天發(fā)現(xiàn),泛型中約束語法又變了,前段時間還是這樣的:
type?Addable?interface?{
?type?int,?int8,?int16,?int32,?int64,?uint,?uint8,?uint16,?uint32,?uint64,?uintptr,?float32,?float64,?complex64,?complex128,?string
}
現(xiàn)在改為這樣了:
type?Addable?interface?{
?int?|?int8?|?int16?|?int32?|?int64?|?uint?|?uint8?|?uint16?|?uint32?|?uint64?|?uintptr?|?float32?|?float64?|?complex64?|?complex128?|?string
}
所以這是最終的方案。
為了方便大家試驗 tip 版本,Go 官方終于做了一件事,那就是新開一個 playground 支持 tip 版本。這樣大家可以不用下載 tip 版本就可以試用 tip 的相關(guān)功能,這就是 https://gotipplay.golang.org/,請自行解決訪問問題。
忍不住趕緊試用了一下:
package?main
import?(
?"fmt"
?"runtime"
)
type?Addable?interface?{
?int?|?int8?|?int16?|?int32?|?int64?|?uint?|?uint8?|?uint16?|?uint32?|?uint64?|?uintptr?|?float32?|?float64?|?complex64?|?complex128?|?string
}
func?Add[T?Addable](a,?b?T?"T?Addable")?T?{
?return?a?+?b
}
func?main()?{
?fmt.Println(runtime.Version())
?fmt.Println(Add(1,?2))
?fmt.Println(Add(2.1,?3.2))
?fmt.Println(Add("程序員",?"幽鬼"))
}
https://gotipplay.golang.org/p/vtXyZInsmRk
輸出:
devel?go1.18-8c73f80400?Thu?Nov?11?15:34:02?2021?+0000
3
5.300000000000001
程序員幽鬼
后續(xù)大家試驗 tip 新功能可以通過它來進(jìn)行,方便快捷。
我是 polarisxu,北大碩士畢業(yè),曾在 360 等知名互聯(lián)網(wǎng)公司工作,10多年技術(shù)研發(fā)與架構(gòu)經(jīng)驗!2012 年接觸 Go 語言并創(chuàng)建了 Go 語言中文網(wǎng)!著有《Go語言編程之旅》、開源圖書《Go語言標(biāo)準(zhǔn)庫》等。
堅持輸出技術(shù)(包括 Go、Rust 等技術(shù))、職場心得和創(chuàng)業(yè)感悟!歡迎關(guān)注「polarisxu」一起成長!也歡迎加我微信好友交流:gopherstudio
評論
圖片
表情
