Reputation: 8997
I was recently playing with the Go language and I bumped into something a bit weird to say the least, let's consider a very simple function:
func main() {
n, e := fmt.Println(`He said: "Hello"`)
fmt.Printf("%T\n", n)
}
Which outputs what I was expecting:
He said: "Hello"
int
Now if I want to display the type of e
:
func main() {
n, e := fmt.Println(`He said: "Hello"`)
fmt.Printf("%T\n", e)
}
and this time prints out:
He said: "Hello"
<nil>
I get the part that there is no error so e
is an empty pointer: nil
but I would have not expected to be a ~~type~~ on its own.
Why am I not getting the actual type?
If so, is there a workaround? (not saying my use case is a realistic one but curious if there is any possibility)
Upvotes: 2
Views: 127
Reputation: 17071
e
is an empty pointer
Nope, error
itself - interface, so you won't have type here.
Upvotes: 2
Reputation: 166626
The Go Programming Language Specification
The predeclared type error is defined as
type error interface { Error() string }
It is the conventional interface for representing an error condition, with the nil value representing no error.
An interface type specifies a method set called its interface. A variable of interface type can store a value of any type with a method set that is any superset of the interface. Such a type is said to implement the interface. The value of an uninitialized variable of interface type is nil.
When storage is allocated for a variable, either through a declaration or a call of new, or when a new value is created, either through a composite literal or a call of make, and no explicit initialization is provided, the variable or value is given a default value. Each element of such a variable or value is set to the zero value for its type: nil for interfaces.
A zero-value error
type, an interface, has no type.Its value is nil
.
Upvotes: 5