英文:
Why is "err != nil"?
问题
我有一个情况,变量"err error"的值只能是"nil",但是一旦被重新赋值,断言"(err == nil) == false"就会出现。
以下是示例代码:
package main
import (
"fmt"
"log"
)
type TestError struct {
Message string
}
func (e *TestError) Error() string {
return e.Message
}
func NewTestError(err error) *TestError {
if err == nil {
return nil
}
log.Printf("NewTestError( ... ): creating new NewTestError err = %s", err)
return &TestError{Message: err.Error()}
}
func main() {
var err error
_, err = fmt.Printf("excuse.\n")
err = NewTestError(err)
log.Printf("main( ... ): err == nil. %v", (err == nil))
log.Printf("main( ... ): err = %#v", err)
}
我从上面的代码中得到以下输出:
excuse.
2015/07/30 08:28:28 main( ... ): err == nil. false
2015/07/30 08:28:28 main( ... ): err = (*main.TestError)(nil)
这两行输出是如何产生的呢?
英文:
I have a situation where the value of a variable "err error" value can only be "nil" but asserts "( err == nil ) == false" once it has been reassigned.
Example code below:
package main
import (
"fmt"
"log"
)
type TestError struct {
Message string
}
func (e *TestError) Error() string {
return e.Message
}
func NewTestError(err error) *TestError {
if err == nil {
return nil
}
log.Printf("NewTestError( ... ): creating new NewTestError err = %s", err)
return &TestError{Message: err.Error()}
}
func main() {
var err error
_, err = fmt.Printf("excuse.\n")
err = NewTestError(err)
log.Printf("main( ... ): err == nil. %v", (err == nil))
log.Printf("main( ... ): err = %#v", err)
}
I get the following output from the above code:
excuse.
2015/07/30 08:28:28 main( ... ): err == nil. false
2015/07/30 08:28:28 main( ... ): err = (*main.TestError)(nil)
How can those last two lines be output?
答案1
得分: 2
对于一个接口值(比如一个error
值)与nil
相等,实际包含的值和实际包含的类型都必须是nil
。在你的情况下,你有一个接口值,它持有一个nil
指针,但是类型是*TestError
(即非nil
)。
PS. 以防不清楚这些“接口值”是什么,你可以查看这个链接:http://research.swtch.com/interfaces
英文:
For an interface value (like an error
value) to compare equal to nil
, both the actual contained value and the actual contained type have to be nil
. In your case you have an interface value, which holds a nil
pointer, but a *TestError
(i.e. non-nil
) type.
PS. Just in case it's not clear what are these "interface values", you can check this http://research.swtch.com/interfaces
答案2
得分: 0
在第二种情况下,你打印的是接口实例的信息,包括类型和值,类型是(*main.TestError)
,值是(nil)
。而在第一种情况下,你实际上比较的不是nil
,因为它也是接口。
英文:
In the second case you're printing the interface instances information which is the type and the value, type being (*main.TestError)
value being (nil)
. In the first case what you're actually comparing isn't nil
because it's also the interface.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论