Interface is just a set of method signatures that type must have in order to implement that particular interface. So you can't call interface.
In your example code DBRepo
is supposed to implement Repository
interface and function list()
is a function that allows to list contents of any type that implements Repository
. In to do so obviously list()
needs to know which instance of Repository
-like type to list - e.g. receive it as an argument. Like this:
func list(ctx *gin.Context, repo Repository) {
// here call GetAll() which MUST exist on all types passed (otherwise they don't
// implement Repository interface
res, _ := repo.GetAll()
// ...
}
Now gin
wouldn't be able to take modified list as a router function because signature of such is just (ctx *gin.Context)
but you can use anonymous function and wrap your Repository-aware list()
in it.
func ApplyRoutes(repo Repository, r *gin.RouterGroup) {
brand := r.Group("/brand") {
brand.GET("/", func(ctx *gin.Context) {
list(repo)
})
}
}
Also your ApplyRoutes()
function needs to know on which Repository routes should operate - I added it here as argument for simplicity, other elegant solution would be to wrap entire controller in type and obtain the Repository
instance as a field of receiver.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…