Background
I am trying to Unmarshal an item returned by dynamodb.GetItem
into an object, which type I do not know at that place. For this I have a function emptyItemConstructor
which returns a new object t of the desired type.
Question
I have a function like this:
func GetItem(emptyItemConstructor func() interface{}) interface{} {
myItem := emptyItemConstructor()
fmt.Printf("Type is: %T
", myItem)
_ = dynamodbattribute.UnmarshalMap(item, &myItem)
fmt.Printf("Type now is: %T
", myItem)
}
and I am passing this function for emptyItemConstructor
:
func constructor() MyDynamoDBItemType {
return MyDynamoDBItemType{}
}
The output of the function is:
Type is: MyDynamoDBItemType
Type now is: map[string]interface
Why is UnmarshalMap changing the type of myItem?
The type of variable myItem
is interface{}
, and the type of UnmarshalMap
input param is interface{}
too. There is no comparison of underlying types when assigning values
A example is as follows:
package main
import "fmt"
func Item() interface{} {
return struct {
Name string
}{Name: "poloxue"}
}
func ItemMap(item *interface{}) {
*item = map[string]interface{}{
"Name": "poloxue",
}
}
func main() {
m := Item()
fmt.Printf("%T
", m)
ItemMap(&m)
fmt.Printf("%T
", m)
}
If you want to unmarshal map to struct , try mapstructure package?
Your function is far too complex. Stop trying to force a "generics" mindset into Go. Just do this:
func GetItem(i interface{}) {
_ = dynamodbattribute.UnmarshalMap(item, &i)
}
But don't ignore errors:
func GetItem(i interface{}) error {
return dynamodbattribute.UnmarshalMap(item, &i)
}
But then you don't need your function at all... just use
dynamodbattribute.UnmarshalMap(item, &i)
as intended.