1

In reflection package I see the code like

    return float64(*(*float32)(v.ptr))

What is *(*float32)(v.ptr)? I don't have any ideas

  • 1
    @JimB that's similar but much, much simpler than the code quoted in the question, which involves a combination of conversion, assertion, and dereferencing. – Adrian Feb 12 '19 at 21:21

1 Answers1

2

Let's unwrap the expression. We'll take it from innermost to outermost, since that's the order it's evaluated:

(*float32)(v.ptr)

Convert v.ptr to *float32, a pointer to a float32.

*(*float32)(v.ptr)

Dereference that pointer, giving us a float32 value.

float64(*(*float32)(v.ptr))

Convert the float32 value to a float64 value.

So, whatever v.ptr is, it's converted to a float32 pointer, dereferenced, and then converted to float64, and returned.

Adrian
  • 42,911
  • 6
  • 107
  • 99
  • FTR, `v.ptr` is an `unsafe.Pointer`, which is how it can be converted into any pointer type. – JimB Feb 12 '19 at 21:40
  • That was my guess but there wasn't enough context given to be sure of its type. – Adrian Feb 12 '19 at 21:46
  • Thank you! That pointer in type conversion made me a little bit confused – Andrew Alferenkov Feb 13 '19 at 20:31
  • It looks a little unusual because of that; the reason is that just `*float32(v.ptr)` would try to convert to a `float32` value and then dereference it (which you can't do because it's not a pointer), so the type has to be wrapped in parens. – Adrian Feb 13 '19 at 20:32
  • If ```unsafe.Pointer``` can be converted into any pointer type why cant we just do smth like ```*(*float64)(v.ptr)``` – Andrew Alferenkov Feb 13 '19 at 20:33
  • Because that's not the actual underlying type. That would take the next 64 bits of memory starting at the pointer location and treat it as a `float64`, when the actual value is only 32 bits long. – Adrian Feb 13 '19 at 20:35
  • @Adrian Now I understand this. Thank you very much again! – Andrew Alferenkov Feb 13 '19 at 20:36