2

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"?

3
  • I doubt that the order in which struct fields are initialized is requlated by the spec (but did not check) so it is okay for the compiler to do one field first (instead of source order). Commented Feb 7, 2018 at 21:21
  • It could automatically do it this way for speed reasons. i.e. functions take longer to evaluate than anything else Commented Feb 7, 2018 at 21:22
  • 1
    Yes, the order is not specified, so there is no reason to assume that one field will be initialized before the other. Commented Feb 7, 2018 at 21:24

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.