On 12/09/2016 00:27, Dan Kortschak wrote:
On Sun, 2016-09-11 at 19:41 +1000, Kiki Sugiaman wrote:
Not exactly a solution for the faint hearted, hah!
It's long, but not complicated, and in the context of Axel's comment
would be placed in a helper of some variety.
For those at home, it's necessary to take the address of the interface
value so that it's not passed as the interface{} that reflect.ValueOf
(so it retains the Fooer type indirectly via a *Fooer), the first Elem
dereferences that pointer to get the original Fooer, then the second
gets the concrete value in the Fooer, and finally IsNil does what it
says. The only thing here that is possible a trap for novitiates is
that
you need to do the &I, Elem dance.
Um, no you don't ...
If you want to get at the actual interface type being passed in then you
need to do the dance, but in this case the question was about the
pointer in the interface - so we don't care about the Fooer type at all.
ValueOf(f2) is the same as ValueOf(&f2).Elem().Elem(), so
ValueOf(f2).IsNil() is all that is needed here.
Basically, Go will automatically wrap any non-interface type when
assigned to an interface{} (which happens automatically in this case
since ValueOf takes an interface{} argument), so a becomes [a] (where I
use [] to show a containing interface type). If we assign an interface
value b which already wraps c (i.e. b = [c]) then no extra wrapping is
performed and we have [c] becomes [c]. ValueOf assumes that the
automatic wrapping has taken place (usually when using reflect you don't
care about the interface value) so in the first case returns information
about a, but in the second returns information about c.
To get information about b we have to hide that it is an interface so
that it will get wrapped. So we have &b becomes [&b], so then ValueOf
gives information about &b, and ValueOf(&b).Elem() gives information
about b.
However in this case the question was: given b how can I tell if c is
nil. So the answer is ValueOf(b).IsNil().
If you want to use reflection to check if b is nil, then you need
ValueOf(&b).Elem().IsNil() - but you could just use b == nil ...
--
Julian
--
You received this message because you are subscribed to the Google Groups
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.