This is a creation in Article, where the information may have evolved or changed.
conclusion : Since interface in go stores both type and value, if a nil object is assigned to a interface, the interface is non-nil.
Nil in Go is equivalent to NULL, NULL, and none in other languages, and in actual use indicates that a variable is empty . Nil can only be assigned to variables of the pointer, channel, Func, interface, map, or slice type. Panic will be thrown if nil is assigned to another variable.
First look at a code:
PackageMainImport "FMT"typeMyerrorstruct{}func(This *myerror) Error ()string{return ""}funcTest () Error {varP *myerror =Nil /*//check err and Set p if bad () {p = errbad} */ returnPfuncMain () {err: = Test ()ifErr = =Nil{FMT. Println ("Err is nil") }Else{FMT. Println ("Err is not nil") }}
The above code will output:
errisNOT nil
This is because, in order to preserve the original data type, in the underlying implementation of go, a interface saves both the original data type and its corresponding values. When assigning a variable of nil to interface, the interface will be stored as {*myerror, nil}. However, the interface variable is nil only if the type and value of the interface are nil.
Or a different way to explain the problem, because nil means that the variable is empty , if it is assigned to interface, then it is no longer empty , so it will not be equal to nil.
Reference:
1. Nil value and nil for error type in Go
2. Golang: detailed interface and nil
3. Go Nil_error