Is there a straightforward way to convert a struct where some fields are "generic" (interface{}
) into another type which has the same field names but is "strongly-typed" (int
, string
, etc)?
Lets say that, given the definitions:
package main
import (
"fmt"
)
type GenericData struct {
Hard int
Soft interface{}
}
type Data struct {
Hard int
Soft int
}
type GenericDataGenerator func() GenericData
func generateGenericData() interface{} {
return GenericData{1, 2}
}
func returnsGenericDataGenerator() interface{} {
return generateGenericData
}
Does converting from GenericData
to Data
require explicitly casting all interface{}
fields? Is there a more straightforwad way to do this?
func main() {
gd := generateGenericData()
fmt.Println(gd)
fmt.Println(gd.(GenericData))
// Doesn't work, but is straightforward
// fmt.Println(gd.(Data))
// Works, but is not straight forward
fmt.Println(Data{gd.(GenericData).Hard, gd.(GenericData).Soft.(int)})
genDataGenerator := returnsGenericDataGenerator()
// Doesn't work, but is straightforward
//genDataGenerator.(GenericDataGenerator)()
// Works, but is not straight forward
resp := genDataGenerator.(func() interface{})()
fmt.Println(resp.(GenericData))
}
The code can be executed in: https://play.golang.org/p/_UVBi5It1FY