Hi Ian,
thanks for your reply.
After reading and experimenting a lot I think I understand the slight
differences between nil and interface{} with nil value.
The only thing I find confusing is that interface{}(nil) == nil returns
true.
(The reason why I use reflect on interface is that I want to operate slice
with different element types, like []interface{}, []int and so on.)
Best regards,
Xinhu
Am Fr., 11. Jan. 2019 um 01:39 Uhr schrieb Ian Lance Taylor <[email protected]
>:
> On Thu, Jan 10, 2019 at 3:40 PM <[email protected]> wrote:
> >
> > I want to append a nil value using reflect.Append(), but I got a panic:
> reflect: call of reflect.Value.Set on zero Value.
> >
> > This is my code.
> >
> > s := make([]interface{}, 10)
> > v := reflect.ValueOf(nil)
> > reflect.Append(reflect.ValueOf(s), v)
> >
> > So is there a way i can append nil? Currently I do this as workaround:
> >
> > s := make([]interface{}, 10)
> > s0 := make([]interface{}, 1)
> > r := reflect.AppendSlice(reflect.ValueOf(s), reflect.ValueOf(s0))
> >
> > It works but I think there must be a better way.
>
> First you have to clearly distinguish between nil, an uninitialized
> value with no type, and the value interface{}(nil), which is an
> uninitialized value of type interface{}. You want the latter. Then,
> it's always a bit awkward to work with interface types with the
> reflect package, because the reflect package naturally tries to look
> for the value stored in the interface type, whereas you actually want
> the interface type.
>
> Here is one way to do it:
>
> https://play.golang.org/p/Qt5-AmYa9Mk
>
> Ian
>
--
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 [email protected].
For more options, visit https://groups.google.com/d/optout.