隐式接口调用函数

huangapple go评论91阅读模式
英文:

Implicit interface call function

问题

在使用Golang的net/http包来服务器静态文件时,我找到了实现FileSystem接口的Dir类型。

一些示例展示了如何使用以下代码来服务器静态文件:

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

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

英文:

Looking for some examples to server static files with net/http package in Golang, I found the type Dir which implements FileSystem interface.

Some examples show You can server static files with the following:

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

What exactly is http.Dir("/tmp") ? It looks like a constructor function for FileSystem.

答案1

得分: 1

http.Dir("/tmp")实际上是一种类型转换,将字符串"/tmp"转换为http.Dir类型。查看文档,你会发现http.Dir实际上是一个字符串类型。因此,这种类型转换是有效的。

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

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

英文:

http.Dir("/tmp") is actually a type conversion where you convert the string /tmp into the http.Dir type. Looking at the docs, you will see that http.Dir is actually a string type. Hence, this type conversion works.

In addition, the http.Dir type also implements the func Open(name string) (File, error) function. Hence, it can be used anywhere where a FileSystem interface is used.

You can also check out the func ServeFile(w ResponseWriter, r *Request, name string) function in the net/http package.

huangapple
  • 本文由 发表于 2017年8月13日 12:03:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/45656937.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定