Reputation: 231
When initializing a struct type using data from a possible 'nil' pointer, the panic message always refers to the first line calling a function in that pointer, instead of a value.
https://play.golang.org/p/VgX59Y08syi
For example, if you swap lines 20 and 21 in the above code, the panic occurs in the line where a function is called, instead of the first dereference to the nil pointer.
Why this happens, instead of the panic happening on "myStruct.MyString"?
Upvotes: 2
Views: 399
Reputation: 1992
By changing func (m *MyStruct) Sent() bool {
(pointer receiver) to func (m MyStruct) Sent() bool {
(value receiver) you can see that the stacktrace changed from
goroutine 1 [running]:
main.(*MyStruct).Sent(...)
/tmp/sandbox520127412/main.go:14
main.main()
/tmp/sandbox520127412/main.go:21 +0x1a
into
goroutine 1 [running]:
main.MyStruct.Sent(...)
/tmp/sandbox497151564/main.go:21
main.main()
/tmp/sandbox497151564/main.go:21 +0x1a
which tell us that golang treat pointer receiver differently.
If you check https://golang.org/ref/spec#Order_of_evaluation, the struct order never was specified. But function call is evaluated first in this case, the mentioned behaviour is not guaranteed in another version of compiler as far as the spec states.
Upvotes: 1