How does this code compile?

blov · · 435 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<pre><code>type Middleware = func(http.Handler) http.Handler func MustLogin(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { next.ServeHTTP(w,r) }) } </code></pre> <p>here is my signature and an example middleware. Everything is fine just what i cannot understand is MustLogin is a middleware and supposedly will return a http.Handler but how come compiler doesnt complain that the <code>HandlerFunc</code> is not a <code>http.Handler</code> because it doesnt have a <code>ServeHttp</code> method so it doesn&#39;t implement the <code>http.Handler</code> interface</p> <hr/>**评论:**<br/><br/>anossov: <pre><blockquote> <p>it doesnt have a ServeHttp method</p> </blockquote> <p>Sure it does: <a href="https://golang.org/pkg/net/http/#HandlerFunc.ServeHTTP" rel="nofollow">https://golang.org/pkg/net/http/#HandlerFunc.ServeHTTP</a></p> <p><a href="https://golang.org/src/net/http/server.go?s=57023:57070#L1904" rel="nofollow">https://golang.org/src/net/http/server.go?s=57023:57070#L1904</a></p></pre>nefthias: <pre><p>oh so that was what i was missing</p></pre>TheMerovius: <pre><p>HandlerFunc does have a <a href="https://godoc.org/net/http#HandlerFunc.ServeHTTP" rel="nofollow">ServeHTTP</a> method.</p></pre>nefthias: <pre><p>yes i figured that right now </p></pre>shovelpost: <pre><blockquote> <p>but how come compiler doesnt complain that the HandlerFunc is not a http.Handler because it doesnt have a ServeHttp method so it doesn&#39;t inherit the http.Handler interface</p> </blockquote> <p>Type <a href="https://golang.org/pkg/net/http/#HandlerFunc" rel="nofollow"><code>http.HandlerFunc</code></a> has a <a href="https://golang.org/pkg/net/http/#HandlerFunc.ServeHTTP" rel="nofollow"><code>ServeHTTP</code></a> method.</p> <p>Also don&#39;t forget that interfaces in Go are satisfied implicitly. There&#39;s no &#34;inheritance&#34; involved.</p></pre>nefthias: <pre><p>I intended to use the word implement fixing it now</p></pre>

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

435 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传