亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Go:自己的 List 類型與自己的 Functor 類型不兼容

Go:自己的 List 類型與自己的 Functor 類型不兼容

Go
慕妹3146593 2023-01-03 11:26:20
為了更多地了解Go、泛型和函數式編程,我實現了一個List類型(摘自list.go):package funcprogtype Function[T any] func(T) Ttype List[T any] []Tfunc (l List[T]) Map(f Function[T]) List[T] {    var ys List[T]    for _, x := range l {        y := f(x)        ys = append(ys, y)    }    return ys}效果很好(main.go):package mainimport (    "fmt"    "funcprog")func main() {    numbers := funcprog.List[int]{0, 1, 2, 3}    twice := func(x int) int { return x * 2 }    fmt.Println(numbers.Map(twice))}$ go run main.go[0 2 4 6]我List的其實是一個Functor,所以我寫了這個接口(functor.go):package funcprogtype Functor[T any] interface {    Map(Function[T]) Functor[T]}但是,如果我想將我List的用作Functor( main.go,已修改):import (    "fmt"    "funcprog")func demo[T int](f funcprog.Functor[T]) {    fmt.Println(f.Map(func(x T) T { return x * 2 }))}func main() {    numbers := funcprog.List[int]{0, 1, 2, 3}    demo[int](numbers)}我收到此錯誤:funcprog.List[int] does not implement funcprog.Functor[int] (wrong type for Map method)    have Map(f funcprog.Function[int]) funcprog.List[int]    want Map(funcprog.Function[int]) funcprog.Functor[int]我的不List[int]也是一個Functor[int],因為List[T]滿足Functor[T]嗎?
查看完整描述

2 回答

?
UYOU

TA貢獻1878條經驗 獲得超4個贊

當查看一個類型是否實現了一個接口時,go 不會嘗試對該函數簽名的元素進行“接口映射”,它只會比較確切的簽名。


如果你想讓你的List[T]類型實現你的Functor[T]接口,你應該改變Map()方法的簽名:


func (l List[T]) Map(f Function[T]) Functor[T] {

    ...

}

額外提一點:這與泛型無關,而是與如何在接口上實現類型檢查有關。


這是另一個例子(沒有泛型):


type MyStr string


// MyStr implements fmt.Stringer

func (s MyStr) String() string {

    return string(s)

}


// but this method does not fulfill the Concatter interface below

func (s MyStr) Concat(x string) MyStr {

    return s + " " + MyStr(x)

}


type Concatter interface {

    Concat(s string) fmt.Stringer

}


var _ Concatter = MyStr("") // compilation error

https://go.dev/play/p/tKDGEXlYHyl


查看完整回答
反對 回復 2023-01-03
?
慕絲7291255

TA貢獻1859條經驗 獲得超6個贊

函數簽名中的類型必須完全匹配。所以你只需要改變List.Map方法的返回類型來返回一個Functor[T].

func (l List[T]) Map(f Function[T]) Functor[T]

現在可以編譯了,因為List[T]確實用它自己的方法實現 ,并且實例化 和共享相同的具體類型。Functor[T]MapdemoList

固定游樂場:https ://go.dev/play/p/a4GeqXstjct

我的List[int]不也是Functor[int]嗎,因為List[T]滿足Functor[T]?

是的,但是 Go generics不支持任何形式的 type variance,因此List[T]在您的示例中返回方法簽名不同于接口的方法簽名。


查看完整回答
反對 回復 2023-01-03
  • 2 回答
  • 0 關注
  • 139 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號