猿问

Go中File和Writer之间的关系是什么?

我只是在阅读 Go 并看到了这段代码


func main(){

s:=`<html>removed content for brevity</html>`

    newfile, err := os.Create("index.html")

    if err != nil {

        log.Fatalf("Failed to create file with error: %v", err)


    }

    defer newfile.Close()

    _, _ = io.Copy(newfile, strings.NewReader(s))

}

根据文档,Copy 函数的第一个参数是 Writer 接口,但是在 File struct 文档中我找不到对该接口的任何引用。


func Copy(dst Writer, src Reader) (written int64, err error)

我假设 File 结构实现了 Writer 接口,但我想知道在学习语言时如何识别这种类型的依赖关系?


谢谢,


Cats萌萌
浏览 176回答 1
1回答

梵蒂冈之花

https://golang.org/pkg/os/#Create包中的Create()方法os返回 a*File作为其值之一。您可以说File结构实现了Writer接口,因为它实现了Write()方法,正如您所猜测的那样,这是 Writers 的要求。File.Write() 实现:https ://golang.org/pkg/os/#File.Write编写器接口:https ://golang.org/pkg/io/#Writer您可能还想查看有关接口的文档:&nbsp;https ://golang.org/doc/effective_go.html#interfaces_and_types
随时随地看视频慕课网APP

相关分类

Go
我要回答