go在函数调用中如何推断参数值?

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

How does go infer a parameter value in a function call?

问题

我对golang还比较新,但对其他面向对象的语言(如Java的lambda表达式)有经验。

当在baseHandler中没有显式传递参数,并且router.GET的第二个参数期望...Handlers时,调用router.GET("/", baseHandler)是如何工作的?

package main
import "github.com/gin-gonic/gin"
func baseHandler(c *gin.Context){
   c.JSON(200, gin.H{
       "message": "hello world",
   })
}
func main() {
   router := gin.Default()
   router.GET("/", baseHandler)
   router.Run()
}

在这段代码中,router.GET("/", baseHandler)的作用是将baseHandler函数与HTTP GET请求的根路径"/"绑定起来。当收到根路径的GET请求时,Gin框架会自动调用baseHandler函数来处理该请求。这里的baseHandler函数没有显式地接受任何参数,但Gin框架会将请求的上下文c *gin.Context作为隐式参数传递给baseHandler函数。通过这个上下文对象,你可以获取请求的信息并进行相应的处理,例如返回一个JSON响应。

希望对你有帮助!如果有任何其他问题,请随时提问。

英文:

I am fairly new to golang but with exp with other OOP languages (java's lambda as well).

How does the call router.GET("/", baseHandler) works when a parameter is not explicitly passed in baseHandler and 2nd argument in router.GET expects ...Handlers

package main
import "github.com/gin-gonic/gin"
func baseHandler(c *gin.Context){
   c.JSON(200, gin.H{
       "message": "hello world",
   })
}
func main() {
   router := gin.Default()
   router.GET("/", baseHandler)
   router.Run()
}

答案1

得分: 2

一个HandlerHandlerFunc类型的,其定义如下:

type HandlerFunc func(*Context)

所以,router.GET接收一个函数变量baseHandler作为参数。当路由器调用baseHandler时,会将一个*Context传递给它。

英文:

A Handler is of type HandlerFunc, which is

type HandlerFunc func(*Context)

So router.GET is passed a function variable, the baseHandler. When the router calls baseHandler, it passes a *Context to it.

答案2

得分: 1

函数可以作为值使用。baseHandler没有传递任何参数,因为它没有被调用。

英文:

Functions can be used as values. baseHandler is not being passed any parameters because it is not being called.

huangapple
  • 本文由 发表于 2021年9月25日 01:28:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/69319048.html
匿名

发表评论

匿名网友

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

确定