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

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

Basic + Slice + Map 類型兼容泛型?

Basic + Slice + Map 類型兼容泛型?

Go
搖曳的薔薇 2022-12-05 17:20:12
有沒有辦法創建一個通用函數,在傳遞映射或切片類型與基本類型時可以調整其操作?目標創建一個具有靈活返回類型的切片讀取函數生成器:func ValueReader[T <probably something fancy>](i int) func ([]ProtoConvertable) T {    return func (row []ProtoConvertable) T {        return ...    }}row := []ProtoConvertable{    &Data[int]{Value: 333},    &ListData{Values: []ProtoConvertable{        &Data[string]{Value: "hello"},        &Data[string]{Value: "world"},    }},    MapData{Values: map[ProtoConvertable]ProtoConvertable{        &Data[int]{Value: 22}: &Data[string]{Value: "world"},        &Data[int]{Value: 11}: &Data[string]{Value: "hello"},    }},}dataReader := ValueReader[int](0) // A function that converts the first element to an intlistDataReader := ValueReader[[]string](1) // A function that converts the second element to a slicemapDataReader := ValueReader[map[int]string](2) // A function that converts the third element to a mapdata := dataReader(row) // 333listData := listDataReader(row) // []string{"hello", "world"}mapData := mapDataReader(row) // map[int]string{11: "hello", 22: "world"}類型type ValueType interface {    int | string}type ProtoConvertable interface {    ToProto() *pb.GenericMessage}type Data[T ValueType] struct {    Value T}func (d *Data) ToProto() *pb.GenericMessage{    ...}type ListData struct {    Values []ProtoConvertable}func (d *ListData) ToProto() *pb.GenericMessage {    ...}type MapData struct {    Values map[ProtoConvertable]ProtoConvertable}func (d *MapData) ToProto() *pb.GenericMessage {    ...}當前解決方案func ValueReader[T ValueType](i int) func([]ProtoConvertable) T {    return func(row []ProtoConvertable) T {        return row[i].(*Data[T]).Value    }}func ListValueReader[T ValueType](i int) func([]ProtoConvertable) []T {    return func(row []ProtoConvertable) []T {        vs := row[i].(*ListData).Values        res := make([]T, len(vs))        for i, v := range vs {            res[i] = v.(*Data[T]).Value        }        return res    }}注意:所有這些代碼都是一個更復雜的庫的未經測試的簡化。它可能需要一些調整才能真正工作。
查看完整描述

1 回答

?
智慧大石

TA貢獻1946條經驗 獲得超3個贊

<probably something fancy>不存在。

主要問題是您想要建模一個匹配基值和兩個復合類型的類型參數,其中一個是您想要同時捕獲K和的映射類型V。

即使它存在,它的主體ValueReader也會是一個類型開關,T以返回每個專門的閱讀器函數,因此您現有的涉及少量代碼重復的解決方案總體上似乎只是一個更好的策略。

我的建議是當對不同具體類型的操作T完全相同時使用泛型。您可以在以下位置閱讀更多信息:https ://go.dev/blog/when-generics


查看完整回答
反對 回復 2022-12-05
  • 1 回答
  • 0 關注
  • 98 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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