英文:
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
一个Handler是HandlerFunc类型的,其定义如下:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论