2 回答

TA貢獻(xiàn)1773條經(jīng)驗(yàn) 獲得超3個(gè)贊
看起來(lái)您真正需要該類(lèi)型的唯一兩個(gè)地方是分配它時(shí)以及將其附加到數(shù)組時(shí)。因此,您可以更改函數(shù)以獲取兩個(gè)回調(diào):
func GetStuff(bundleURI string, newItem func() interface{},collect func(interface{})) error {
// instead of var item = new(IP0059T1)
var item = newItem()
...
// instead of items = append(items, *item)
collect(item)
}
并使用以下方法調(diào)用該函數(shù):
items:=make([]Item,0)
GetStuff(uri, func() interface{} {return new(Item)},
func(item interface{}) {items=append(items,*item.(*Item))})

TA貢獻(xiàn)1111條經(jīng)驗(yàn) 獲得超0個(gè)贊
你可以像 Go 標(biāo)準(zhǔn)庫(kù)那樣做,例如 in encoding/json,就是把要填寫(xiě)的值作為參數(shù)。您的“通用”將類(lèi)似于:
GetValues(bundleURI string, dest interface{}) (error)
wheredest應(yīng)該是指向應(yīng)該反序列化為任何類(lèi)型的切片的指針,例如:
var v []IP0059T1
err = GetValues(myURI, &v)
然后,GetValues您可以使用reflect.Type.Elem()獲取切片元素的類(lèi)型,reflect.New()創(chuàng)建該類(lèi)型的新實(shí)例,reflect.Append()并將它們直接附加到dest. 這保留了類(lèi)型安全,同時(shí)允許某種程度的泛型編程。
- 2 回答
- 0 關(guān)注
- 166 瀏覽
添加回答
舉報(bào)