关于 appHandle自定义类型和HandleFileList的调用

来源:3-3 服务器统一出错处理_浏览器需放大

joyefish

2021-12-27 09:35:32

type appHandler func(writer http.ResponseWriter, request *http.Request) error
func errWrapper(handler appHandler) func(http.ResponseWriter, *http.Request) {

这里appHandler是一个自定义的函数类型,errWrapper函数的参数是一个appHandler类型的参数

func HandleFileList(writer http.ResponseWriter, request *http.Request) error {

这是在handler.go种定义实现的HandleFileList,并未显示的指定是appHandler类型,按照Go语言基础知识HandleFileList和appHandler应该是两个不同类型。

为什么在main函数中errWrapper可以直接传入HandleFileList?如下:

http.HandleFunc("/list/", errWrapper(fileListing.HandleFileList))

还麻烦老师解答一下

写回答

1回答

ccmouse

2021-12-28

这是它的规定。我帮同学翻到了原文

这个问题对应其中的这种情况:

A value x is assignable to a variable of type T ("x is assignable to T") if one of the following conditions applies:

  • x's type is identical to T.

  • x's type V and T have identical underlying types and at least one of V or T is not a defined type.

  • T is an interface type and x implements T.

  • x is a bidirectional channel value, T is a channel type, x's type V and T have identical element types, and at least one of V or T is not a defined type.

  • x is the predeclared identifier nil and T is a pointer, function, slice, map, channel, or interface type.

  • x is an untyped constant representable by a value of type T.

这条是说,赋值的话,他们"underlying",我大致翻成实际上,的类型相同。然后等号左右两边至少有一个不是defined type。defined type是指用type xxx 定义的类型,显然appHandler是,但HandleFileList不是。

我们这里虽然是函数传参,但是遵循的是assignment(赋值)的逻辑,相当于把HandleFileList赋值给了一个appHandler。参数列表一样,而且只有一个是defined type,所以满足黑体这一条,可以赋值。


那么我们根据这个规则,试一试两个defined type还能赋值吗?

type appHandler func(writer http.ResponseWriter, request *http.Request) error

type appHandler2 func(writer http.ResponseWriter, request *http.Request) error

var ah appHandler = HandleFileList // 编译通过

var ah2 appHandler2 = ah // 编译错误,此处等号右边必须写成appHandler2(ah)


1
hoyefish
hp>解释非常清楚,感谢老师解答,实际实验如下:

https://img.mukewang.com/climg/61cd018b09d2563809080507.jpg

h021-12-30
共1条回复

0 学习 · 1399 问题

查看课程