登录
首页 >  Golang >  Go问答

HandlerFunc(f) 如何将函数转换为接口类型?

来源:stackoverflow

时间:2024-04-13 13:45:40 216浏览 收藏

哈喽!今天心血来潮给大家带来了《HandlerFunc(f) 如何将函数转换为接口类型?》,想必大家应该对Golang都不陌生吧,那么阅读本文就都不会很困难,以下内容主要涉及到,若是你正在学习Golang,千万别错过这篇文章~希望能帮助到你!

问题内容

在检查以下代码时,对从函数到接口的类型转换有疑问。

代码

http_hello.go:

package main

import (
    "fmt"
    "log"
    "net/http"
)

// hello http,
func hellohttp() {
    // register handler,
    http.handle("/", http.handlerfunc(hellohandler))

    // start server,
    err := http.listenandserve(":9090", nil)
    if err != nil {
        log.fatal("listenandserve:", err)
    }

}

// handler function - hello,
func hellohandler(w http.responsewriter, r *http.request) {
    fmt.fprintf(w, "hello, you've requested: %s\n", r.url.path)
}

func main() {
    hellohttp()
}

上面的代码有效。

(然后我尝试编写一个小程序来检查这是否是一个通用功能,但它不起作用,请检查以下代码)

func_to_intf.go:

package main

import (
    "fmt"
)

// an interface,
type Adder interface {
    add(a, b int) int
}

// alias of a function signature,
type AdderFunc func(int, int) int

// a simple add function,
func simpleAdd(a, b int) int {
    return a + b
}

// call Adder interface to perform add,
func doAdd(a, b int, f Adder) int {
    return f.add(a, b)
}

func funcToIntf() {
    fa := AdderFunc(simpleAdd)
    fmt.Printf("%#v, type: %T\n", fa, fa)

    a, b := 1, 2
    sum := doAdd(a, b, fa)
    fmt.Printf("%d + %d = %d\n", a, b, sum)
}

func main() {
    funcToIntf()
}

输出:

./func_to_intf.go:30:14:无法使用 fa (adderfunc 类型)作为 adder 类型 在 doadd 的参数中:adderfunc 未实现 adder(缺少 add 方法)

问题

  1. http.handlerfunc(hellohandler) 获取 http.handler 类型的值,因为这就是 http.handle() 所期望的,对吗?
  2. 如果是,则意味着它将函数转换为接口类型的值,这是如何发生的?
    • 这是 go 的内置功能吗?

      我做了一个测试(如上面的 func_to_intf.go 所示),似乎没有。

    • 或者,http.handlerfunc 的特殊实现是否实现了这一点?

@update - 摘要

(虽然答案很好地解决了问题,但经过审查和更多测试后,还需要其他几个 go 功能来完全消除最初的疑问,如下所示。) p>

  • 函数类型。

    函数就是值,并且它有类型。

    函数类型可以通过函数签名上的 type 关键字来定义。

    例如 type adderfunc func(int, int) int

  • 函数上的类型转换器 ti(v)

    任何函数都可以转换为具有相同签名的函数类型,只需通过 t(v),使用函数类型名称为 t,实际函数为 v

    然后,当调用新值时,将调用实际函数 v

    例如 fa := adderfunc(simpleadd)

    (在问这个问题之前,这对我来说很模糊,这是我感到困惑的主要原因之一)


解决方案


这是一个简单的类型转换。

在 go 中,除了 structs 之外,你还可以定义自定义类型。在本例中,http.handlerfunc 是函数类型 func(http.responsewriter,*http.request)。由于您的函数与自定义类型具有相同的基础类型(签名),因此可以将其转换为自定义类型。

此外,代码可以在自定义类型上定义方法,无论它是什么底层类型,也无论它是否是 struct 。在这种情况下,http包在其上定义了servehttp方法,当然,它只是调用函数本身。

您可以在这里阅读源代码:https://golang.org/src/net/http/server.go?s=58384:58444#L1936

对于示例代码中的加法器,您可以执行相同的操作:在 adderfunc 上定义一个方法。

func (a AdderFunc) add(x, y int) int {
    return a(x, y)
}

演示:https://play.golang.org/p/5mf_afHLQA2

http.handlerfunc是一个通过提供方法http.servehttp(responsewriter, *request)来满足接口http.handler的类型。

http.handlerfunc(hellohandler) 是一种类型转换,用于转换具有相同底层基类型但不同方法集的类型。

你的例子working

到这里,我们也就讲完了《HandlerFunc(f) 如何将函数转换为接口类型?》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>