Ben Guild
Ben Guild

Reputation: 5146

Need to construct interface/pointer using Reflect in Golang, not working

So, this works:

house := model.House {};
err = db.First(&house).Error;

However, this doesn't work:

var house model.House;

fetchFromDatabase := reflect.New(reflect.TypeOf(house)).Interface();
err = db.First(&fetchFromDatabase).Error;

... The database library gives the error:

unsupported destination, should be slice or struct

To me, that should be a struct, considering the "House" type is a struct. However, I'm still wrapping my head around Reflect ... can anyone help?

Upvotes: 1

Views: 865

Answers (1)

Thundercat
Thundercat

Reputation: 121119

The library is complaining because the application is passing a *interface{} to the method. The value fetchFromDatabase is a pointer to a struct. Pass this value directly to the method:

var house model.House
fetchFromDatabase := reflect.New(reflect.TypeOf(house)).Interface()
err = db.First(fetchFromDatabase).Error

Upvotes: 4

Related Questions