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

注:本文是对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

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

扫码关注云+社区

领取腾讯云代金券