在 Go 中,当一个函数返回错误时,其他变量是否总是它的“零”值?

我说的是 Go 标准库:


output, err := abc.Xyz()

if err != nil {

    // by convention is `output` always its "zero" value?

}


小唯快跑啊
浏览 212回答 1
1回答

富国沪深

不总是。例如io.Reader:包io类型阅读器type&nbsp;Reader&nbsp;interface&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Read(p&nbsp;[]byte)&nbsp;(n&nbsp;int,&nbsp;err&nbsp;error)}Reader 是包装基本 Read 方法的接口。Read 将最多 len(p) 个字节读入 p。它返回读取的字节数 (0 <= n <= len(p)) 和遇到的任何错误。即使 Read 返回 n < len(p),它也可能在调用期间使用所有 p 作为暂存空间。如果某些数据可用但 len(p) 字节不可用,则 Read 通常会返回可用的数据,而不是等待更多数据。当 Read 在成功读取 n > 0 个字节后遇到错误或文件结束条件时,它返回读取的字节数。它可能会从同一个调用中返回(非零)错误或从后续调用中返回错误(和 n == 0)。这种一般情况的一个实例是,在输入流末尾返回非零字节数的 Reader 可能返回 err == EOF 或 err == nil。下一个 Read 应该返回 0,EOF。在考虑错误 err 之前,调用者应始终处理返回的 n > 0 个字节。这样做可以正确处理读取一些字节以及允许的 EOF 行为后发生的 I/O 错误。不鼓励 Read 的实现返回带有 nil 错误的零字节计数,除非 len(p) == 0。调用者应该将返回 0 和 nil 视为表示没有发生任何事情;特别是它不表示EOF。实现不能保留 p。例如,readfile.go:package mainimport (&nbsp; &nbsp; "bufio"&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "io"&nbsp; &nbsp; "os")func main() {&nbsp; &nbsp; f, err := os.Open("readfile.go")&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(err)&nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; }&nbsp; &nbsp; defer f.Close()&nbsp; &nbsp; r := bufio.NewReader(f)&nbsp; &nbsp; fileLen := int64(0)&nbsp; &nbsp; buf := make([]byte, 0, 4*1024)&nbsp; &nbsp; for {&nbsp; &nbsp; &nbsp; &nbsp; n, err := r.Read(buf[:cap(buf)])&nbsp; &nbsp; &nbsp; &nbsp; buf = buf[:n]&nbsp; &nbsp; &nbsp; &nbsp; if n == 0 {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if err == nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; continue&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if err == io.EOF {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(err)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; // Do something with buf&nbsp; &nbsp; &nbsp; &nbsp; fileLen += int64(len(buf))&nbsp; &nbsp; &nbsp; &nbsp; if err != nil && err != io.EOF {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(err)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Println("file length:", fileLen, "bytes")}如果是err != nil这样,除非文档另有说明,否则假定所有其他值都未定义。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go