Before we discuss about the why calling a method on a nil struct pointer doesn't panic,
lets understand about
the zero value of program initialization and execution
.
The Zero Value
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:- false for booleans,
- 0 for numeric types,
- "" for strings, and
- nil for pointers, functions, interfaces, slices, channels, and maps.
Final Thought
In the above example variablebb
is nil, so calling bb.Go()
method is expected to
cause a panic runtime error: invalid memory address or nil pointer dereference, but the
method call succeeds. Why this doesn't panic? Answer to this question explained in the go specification,
this does not panic because: The function to be called by the Expression.Name()
syntax is
entirely determined by the Type of Expression and not by the particular
run-time value of that expression, including nil.
Post a Comment
Post a Comment