golang有类似泛型(java)的东西吗?

时间:2014-01-10 08:07:08

标签: go

我想在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 
}

我希望,它能解释什么是问题

1 个答案:

答案 0 :(得分:2)

您正在尝试将[]ConcreteType转换为[]interface{},这不会隐式执行。

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

相关问题