This question already has answers here:
Why no generics in Go?

(6个答案)


6年前关闭。




我想在golang上写CRUD之类的东西。我看到像
type CRUD interface {
  Save(entity interface{})() // done
  Update(entity interface{})() // done
  Delete(entity interface{})() // done
  All() []interface{} // problem is here
}

我有几种模型结构。
type User struct {
  Login string
  Password string
}

type Comment struct {
  UserId int64
  Message string
  CreatedAt int64
}

我有一些服务:
// 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
}

我希望它将解释什么问题

最佳答案

您正在尝试将[]ConcreteType转换为[]interface{},但不能隐式工作。

但是您可以将[]ConcreteType转换为interface{},然后将其投射回[]ConcreteType.

10-02 08:03