This question already has an answer here:
I want to write something like CRUD on golang. I see that like
type CRUD interface {
Save(entity interface{})() // done
Update(entity interface{})() // done
Delete(entity interface{})() // done
All() []interface{} // problem is here
}
I have several model structures.
type User struct {
Login string
Password string
}
type Comment struct {
UserId int64
Message string
CreatedAt int64
}
and I have some service:
// Struct should implement interface CRUD and use instead of interface{} User struct
type UserService struct {
Txn SomeStructForContext
}
func (rec *UserService) Save(entity interface{}) {
user := entity.(*model.User)
// TODO operation with user
}
// All the same with Update and Delete
func (rec *UserService) All() ([]interface{}) {
// TODO: I can't convert User struct array for return
}
I hope, it'll explain what problem is
</div>
You are trying to convert []ConcreteType
to []interface{}
, which does not work implicitly.
But you can convert []ConcreteType
to interface{}
and then cast it back to []ConcreteType.