美文网首页工作生活
golang-101-hacks(26)——io.Writer

golang-101-hacks(26)——io.Writer

作者: _羊羽_ | 来源:发表于2019-06-30 17:48 被阅读0次

    注:本文是对golang-101-hacks中文翻译

    io.Reader 接口相对应的就是 io.Writer接口了

    type Writer interface {
            Write(p []byte) (n int, err error)
    }
    
    

    io.Reader相比,不需要考虑io.EOF 错误, Write方法很简单:

    Compared to io.Reader, since you no need to consider io.EOF error, the process of Writemethod is simple:
    err == nil 表示所有数据写入成功
    (1) err == nil: All the data in p is written successfully;
    (2) ' err != nil ': 表示p 中的数据部分或都没有写入成功。
    (2) err != nil: The data in p is partially or not written at all.
    查看下面的例子
    Let's see an example:

    package main
    
    import (
            "log"
            "os"
    )
    
    func main() {
            f, err := os.Create("test.txt")
            if err != nil {
                    log.Fatal(err)
            }
            defer f.Close()
    
            if _, err = f.Write([]byte{'H', 'E', 'L', 'L', 'O'}); err != nil {
                    log.Fatal(err)
            }
    }
    
    

    执行程序,test.txt 被创建
    After executing the program, the test.txt is created:

    # cat test.txt
    HELLO
    

    相关文章

      网友评论

        本文标题:golang-101-hacks(26)——io.Writer

        本文链接:https://www.haomeiwen.com/subject/oimbcctx.html