gpt4 book ai didi

go - 隐式接口(interface)调用函数

转载 作者:数据小太阳 更新时间:2023-10-29 03:13:04 26 4
gpt4 key购买 nike

在 Golang 中寻找一些使用 net/http 包服务器静态文件的示例,我找到了实现 FileSystem 接口(interface)的 Dir 类型。

一些示例显示您可以使用以下服务器静态文件:

http.Handle("/", http.FileServer(http.Dir("/tmp")))

http.Dir("/tmp") 到底是什么?它看起来像是 FileSystem 的构造函数。

最佳答案

http.Dir("/tmp") 实际上是一种类型转换,您将字符串 /tmp 转换为 http.Dir类型。看着 docs ,你会看到http.Dir其实是一个字符串类型。因此,这种类型转换有效。

此外,http.Dir 类型还实现了func Open(name string) (File, error) 函数。因此,它可以用在任何有 FileSystem 的地方。使用接口(interface)。

您还可以查看 func ServeFile(w ResponseWriter, r *Request, name string) net/http 包中的函数。

关于go - 隐式接口(interface)调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45656937/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com