【问题标题】:Does golang have something like generic (java)? [duplicate]golang 是否有类似泛型(java)的东西? [复制]
【发布时间】:2014-01-10 08:07:08
【问题描述】:

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

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

【问题讨论】:

  • 关于“golang generic”的搜索应该很容易返回 1)否 2)这是明智的。话虽这么说,我不明白你想做什么。
  • 如果可能的话,你能给我指导寻找解决方案吗?
  • @Rusfearuth,正如您从标志中看到的那样,不清楚您在问什么。
  • @Agis,我明白了。如果这是错误的方式,我会很高兴看到另一个。你没看我之前的评论吗?
  • @Rusfearuth 我们不明白您要做什么以及您面临的问题是什么。你能解释一下吗?

标签: go


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2011-02-27
    • 2021-07-30
    • 2016-08-02
    • 1970-01-01
    • 1970-01-01
    • 2011-01-07
    • 1970-01-01
    • 2012-07-08
    • 1970-01-01
    相关资源
    最近更新 更多