通过给定键从map[string]interface{}调用函数。

huangapple go评论62阅读模式
英文:

calling function from map[string]interface{} by giving key

问题

我想要能够将函数名传递给gin.Engine路由处理程序。我有以下代码:

// 状态服务
type StatusService struct {
App *gin.Engine
}

func (s *StatusService) Ping(ctx *gin.Context) {
ctx.JSON(200, gin.H{
"message": "pong",
})
}

app := gin.Default()
// 定义服务
statusService := &services.StatusService{
App: app,
}
ss := make(map[string]interface{})
ss["auth"] = statusService

app.GET("/ping", ss["auth"].Ping)

编译器给出以下错误:

./app.go:60: ss["auth"].Ping未定义(类型interface {}没有Ping字段或方法)

有关如何修复此问题的任何想法吗?

英文:

I want to be able to pass function name to gin.Engine route handler. I have the following code;

// status service
type StatusService struct {
	App *gin.Engine
}

func (s *StatusService) Ping(ctx *gin.Context) {
	ctx.JSON(200, gin.H{
		"message": "pong",
	})
}

app := gin.Default()
// define services
statusService := &services.StatusService{
    App: app,
}
ss := make(map[string]interface{})
ss["auth"] = statusService

app.GET("/ping", ss["auth"].Ping)

The compiler gives the following error;

./app.go:60: ss["auth"].Ping undefined (type interface {} has no field or method Ping)

Any ideas about how to fix that?

答案1

得分: 2

interface{}适用于几乎任何类型,问题在于你没有断言该对象的类型。在这种情况下,你需要像这样使用... ss["auth"].(*StatusService).Ping(myCtxInstance)。这个答案有一个更详细的示例,我就不重复了;https://stackoverflow.com/questions/6769020/go-map-of-functions

还有一些其他的事情;如果你的真实用例就像你的示例一样简单,那就停止你正在做的事情,并将func(ctx *gin.Context)作为第二个参数添加进去。此外,根据你想要使用的函数的性质(比如它们是否都具有相同的参数和返回类型),你可能希望为委托使用第二个参数,map[string]func(argumentType)可能更合适。

你目前的设计将所有错误都推迟到运行时,显然不如我上面提到的两个选项在编译时的安全性好。

英文:

interface{} works for just about any type, the problem is that you've failed to assert which type the thing is. In this case you would need something like... ss["auth"].(*StatusService).Ping(myCtxInstance). This answer has a more thorough example which I'll refrain from duplicating; https://stackoverflow.com/questions/6769020/go-map-of-functions

Couple other things; if your real use case is as simple as your example just stop what you're doing and add func(ctx *gin.Context) as a second argument. Also, depending on the nature of the functions you want to use (like if they all have the same args and return types) then you might want to use a second arg for the delegates, map[string]func(argumentType) would be more appropriate.

The design you currently have pushes all errors to runtime which obviously is less desirable than the compile time safety you'd get from either of the options I touched on above.

huangapple
  • 本文由 发表于 2015年7月1日 06:40:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/31149756.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定