go 返回错误的时候, 返回的值应该可用吗

2025 年 11 月 6 日
 shimeow

现在写的一个函数, 会返回多种错误, 我想的是在一些错误的时候, 值也是部份可用的, 在另一些错误的时候, 值是不可用的

之前看到有说函数返回错误的时候, 应该默认正常返回的值为 nil, 不知道有没有这个说法

4467 次点击
所在节点    Go 编程语言
32 条回复
paceewang1
2025 年 11 月 6 日
返回 err 了,一般值就认为是失效了,特别是有指针的情况下,但是没有硬性规定,只是一个代码风格问题吧。
但是说实话,没想到有什么情况下是返回了 err ,返回值还部分可用的,这种情况一定是函数里面做了两个步骤,然后其中一个步骤的 err 是可以忽略的,那为什么不拆成两个函数呢。
xg62718
2025 年 11 月 6 日
不可用!
deplives
2025 年 11 月 6 日
@shinonome #6 那这个不叫错误啊
THESDZ
2025 年 11 月 6 日
// 声明类型方便理解
var err error
var warnings []warning
var result xxx
// 调用
err,warnings,result = callfunc(args)
可以参考这种。
dobelee
2025 年 11 月 6 日
你敢用的话可以。
lysShub
2025 年 11 月 6 日
我也问过 https://www.v2ex.com/t/1132824 ,这种情况主要存在于 Read 、Write ,其实没什么用;

自己写的函数还是不要搞这种了
proxychains
2025 年 11 月 6 日
返回的 err!=nil, 那么该函数应当是不可信的, 因为它内部产生了错误.
DefoliationM
2025 年 11 月 6 日
大部分情况不应该,特殊情况应写清楚注释。
everhythm
2025 年 11 月 7 日
可以的,如果情况多的话,类似 http status code
willchen
2025 年 11 月 7 日
那就不应该用错误,你自己定一个状态码呗
iseki
2025 年 11 月 20 日
取决于你的设计,Go 对这个看上去没有强烈观点,因为标准库两种选择都有。
supuwoerc
2025 年 12 月 26 日
```
// Reader is the interface that wraps the basic Read method.
//
// Read reads up to len(p) bytes into p. It returns the number of bytes
// read (0 <= n <= len(p)) and any error encountered. Even if Read
// returns n < len(p), it may use all of p as scratch space during the call.
// If some data is available but not len(p) bytes, Read conventionally
// returns what is available instead of waiting for more.
//
// When Read encounters an error or end-of-file condition after
// successfully reading n > 0 bytes, it returns the number of
// bytes read. It may return the (non-nil) error from the same call
// or return the error (and n == 0) from a subsequent call.
// An instance of this general case is that a Reader returning
// a non-zero number of bytes at the end of the input stream may
// return either err == EOF or err == nil. The next Read should
// return 0, EOF.
//
// Callers should always process the n > 0 bytes returned before
// considering the error err. Doing so correctly handles I/O errors
// that happen after reading some bytes and also both of the
// allowed EOF behaviors.
//
// If len(p) == 0, Read should always return n == 0. It may return a
// non-nil error if some error condition is known, such as EOF.
//
// Implementations of Read are discouraged from returning a
// zero byte count with a nil error, except when len(p) == 0.
// Callers should treat a return of 0 and nil as indicating that
// nothing happened; in particular it does not indicate EOF.
//
// Implementations must not retain p.
type Reader interface {
Read(p []byte) (n int, err error)
}
```
每一个开发者的设计不同,上面的代码是 Reader 的注释,说了应该总是先处理 p ,再处理错误。

我遇到的基本都是有错误只有错误会有意义,其余均是 0 值。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/1170954

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX