有沒有辦法創建一個通用函數,在傳遞映射或切片類型與基本類型時可以調整其操作?目標創建一個具有靈活返回類型的切片讀取函數生成器: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
- 1 回答
- 0 關注
- 98 瀏覽
添加回答
舉報
0/150
提交
取消