2021年2月3日 星期三

Go 泛型

剛看到 Go 已經在 1.18β版中支援泛型。

在這寫個範例 code:

package main

import (
	"fmt"
)

type Vegetable struct {
	Name   string
	Color  string
	Energy float64
}

type Fruit struct {
	Name  string
	Color string
}

// 泛型 VegeFood ,可視為 Fruit 也可視為 Vegetable
type VegeFood interface {
	type Fruit, Vegetable
}

func main() {
	test(Fruit{Name: "banana", Color: "yellow"})
	test(Vegetable{Name: "Spinacia oleracea", Energy: 23.0, Color: "green"})
}

func test[C VegeFood](ab C) {
	fmt.Printf("%#v\n", ab)
}

說實在的,一方面很高興 Go 終於要支援泛型;但一方面,這種語法真的很不習慣。

其他人都是用 >< 來標示泛型,但 Go 居然選用中括號?!

至於使用 interface 的設計,這也是個不習慣的點,但我覺得這個讓泛型變得清晰,你能確保這裡只會出現那些類型的參數。不用像 Java 那樣,是限定特定 interface 的

參考資料

Ian Lance Taylor (2021) A Proposal for Adding Generics to Go. The Go Blog. Retrieved from https://blog.golang.org/generics-proposal

沒有留言:

張貼留言