代码之家  ›  专栏  ›  技术社区  ›  mbarkhau

功能实现接口

go
  •  10
  • mbarkhau  · 技术社区  · 16 年前

    我想知道这里发生了什么。

    存在HTTP处理程序的接口:

    type Handler interface {
        ServeHTTP(*Conn, *Request)
    }
    

    我认为我理解这个实现。

    type Counter int
    
    func (ctr *Counter) ServeHTTP(c *http.Conn, req *http.Request) {
        fmt.Fprintf(c, "counter = %d\n", ctr);
        ctr++;
    }
    

    根据我的理解,类型“counter”实现接口,因为它有一个具有所需签名的方法。到现在为止,一直都还不错。然后给出这个例子:

    func notFound(c *Conn, req *Request) {
        c.SetHeader("Content-Type", "text/plain;", "charset=utf-8");
        c.WriteHeader(StatusNotFound);
        c.WriteString("404 page not found\n");
    }
    
    // Now we define a type to implement ServeHTTP:
    type HandlerFunc func(*Conn, *Request)
    func (f HandlerFunc) ServeHTTP(c *Conn, req *Request) {
        f(c, req) // the receiver's a func; call it
    }
    // Convert function to attach method, implement the interface:
    var Handle404 = HandlerFunc(notFound);
    

    有人能详细说明这些不同的功能为什么或如何结合在一起吗?

    2 回复  |  直到 16 年前
        1
  •  13
  •   user181548    16 年前

    这是:

    type Handler interface {
        ServeHTTP(*Conn, *Request)
    }
    

    说任何一种满足 Handler 接口必须具有 ServeHTTP 方法。以上都在包裹里 http .

    type Counter int
    
    func (ctr *Counter) ServeHTTP(c *http.Conn, req *http.Request) {
        fmt.Fprintf(c, "counter = %d\n", ctr);
        ctr++;
    }
    

    这会在对应于servehtp的计数器类型上放置一个方法。这是一个独立于以下内容的示例。

    据我所知, 类型“counter”实现 接口,因为它有一个方法 具有所需的签名。

    这是正确的。

    以下函数本身不能作为 处理程序 :

    func notFound(c *Conn, req *Request) {
        c.SetHeader("Content-Type", "text/plain;", "charset=utf-8");
        c.WriteHeader(StatusNotFound);
        c.WriteString("404 page not found\n");
    }
    

    其余的这些东西只是符合上面的内容,所以它可以是一个 处理程序 .

    在下面,a HandlerFunc 是一个接受两个参数的函数, 指针指向 Conn 和 指向的指针 Request ,什么也不返回。换句话说,任何接受这些参数而不返回任何值的函数都可以是 手柄功能 .

    // Now we define a type to implement ServeHTTP:
    type HandlerFunc func(*Conn, *Request)
    

    在这里 Service HTTP 是添加到类型的方法 汉德尔芬克 :

    func (f HandlerFunc) ServeHTTP(c *Conn, req *Request) {
        f(c, req) // the receiver's a func; call it
    }
    

    它所做的就是调用函数本身( f )给出了参数。

    // Convert function to attach method, implement the interface:
    var Handle404 = HandlerFunc(notFound);
    

    在上面的行中, notFound 已最终确定接口可接受 处理程序 通过人为地从函数本身创建一个类型实例并将函数 Service HTTP 实例的方法。现在 Handle404 可用于 处理程序 接口。这基本上是一种技巧。

        2
  •  1
  •   Dan Lorenc    16 年前

    下半场你到底不明白什么?和上面的图案一样。不是将计数器类型定义为int,而是定义一个名为notfound的函数。然后,他们创建一种称为handlerFunc的函数类型,该函数接受两个参数,一个连接和一个请求。然后,他们创建一个名为servehtp的新方法,该方法绑定到handlerFunc类型。handle404只是使用notfound函数的此类的一个实例。