开发中遇到一个问题,在如下代码中, 35 到 41 行的位置switch语句的default分支(Point A), 本意是用匿名结构体实现接口, 匿名结构体的作用就是返回resource not found 反馈给调用者, 但是发现在代码中很难给一个匿名结构体添加一个方法并使其符合某个接口. 我知道将返回类型改写为函数类型而不是接口类型, 可以解决遇到的问题.
**但是我发这个篇文章的目的是想探讨一下, 如何给一个匿名结构体添加方法,并让它符合某个接口**
以下是编译器在代码 第35行(Pinter A) 给出的提示信息
Cannot use 'struct { handle func(w http.ResponseWriter, d []byte, r *http.Request, id string) }{ func(w http.ResponseWriter, d []byte, r *http.Request, id string){ http.NotFound(w, r) }, }' (type struct {...}) as type MediaHandler in assignment Type does not implement 'MediaHandler' as 'handle' method is missing l
```go
package captcha
import (
"bytes"
"io"
"net/http"
"path"
"strings"
"time"
)
type MediaHandler interface {
handle(w http.ResponseWriter, d []byte, r *http.Request, id string)
}
type captchaHandler struct {
imgWidth int
imgHeight int
}
func (h *captchaHandler) createMediaHandler( r *http.Request) MediaHandler {
dir, file := path.Split(r.URL.Path)
ext := path.Ext(file)
lang := strings.ToLower(r.FormValue("lang"))
download := path.Base(dir) == "download"
var mediaHandler MediaHandler
switch ext {
case ".png":
mediaHandler = &ImgHandler{h.imgWidth, h.imgHeight, download}
case ".wav":
mediaHandler = &AudioHandler{lang, download}
default:
mediaHandler = struct { //Point A: compile error , struct can't be assigned to mediaHandler
handle func(w http.ResponseWriter, d []byte, r *http.Request, id string)
}{
func(w http.ResponseWriter, d []byte, r *http.Request, id string){
http.NotFound(w, r)
},
}
}
return mediaHandler
}
```
有疑问加站长微信联系(非本文作者))