how to declare type as interface{}

95 views
Skip to first unread message

Alexander Mills

unread,
Sep 3, 2020, 4:32:52 PM9/3/20
to golang-nuts
This works:

var z interface{}
if err := json.NewDecoder(resp.Body).Decode(&z); err != nil {
     t.Fatal(err)
}

but this doesn't work:

if err := json.NewDecoder(resp.Body).Decode(&interface{}{}); err != nil {
     t.Fatal(err)
}

and this doesn't work:

if err := json.NewDecoder(resp.Body).Decode(&struct{}{}); err != nil {
     t.Fatal(err)
}


my goal is to unmarshal to an anonymous variable and discard it, as part of a test. Is there a way to do this?

Axel Wagner

unread,
Sep 3, 2020, 4:53:53 PM9/3/20
to Alexander Mills, golang-nuts
What's wrong with the first one?
The second one doesn't work because there are not interface composite literals. So you need to actually have an interface{} variable to take the address of.
The third one seems to work just fine: https://play.golang.org/p/zn2mL69VzPo

--
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...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/8f58f470-8055-49bc-a248-92a496473f8bn%40googlegroups.com.

Brian Candler

unread,
Sep 3, 2020, 4:59:33 PM9/3/20
to golang-nuts
You can't take the address of an arbitrary value or expression, although you can for composite literals which is why &struct{}{} is OK.
https://golang.org/ref/spec#Address_operators

Harald Weidner

unread,
Sep 3, 2020, 6:25:58 PM9/3/20
to golang-nuts
Hello,

> but this doesn't work:
>
> if err := json.NewDecoder(resp.Body).Decode(&interface{}{}); err != nil {
> t.Fatal(err)
> }

You can use new(interface{}).

See https://play.golang.org/p/s85MwlDygBG

Harald
Reply all
Reply to author
Forward
0 new messages