NimaKapoor
NimaKapoor

Reputation: 133

Is it possible to have interface composite literals in Go?

I just want to confirm if my understanding is correct about interface{}{}

Does interface{}{} mean a composite literal of interface type?

So, if I wanted to pass a composite type, lets say []byte as a interface{}, I should assign it to a variable of type interface{}{} and pass in that variable, whereas if I wanted to pass a non composite type, such as a int as a interface{}, I should assign it to a variable of type interface{} and pass in that variable.

Is my understanding correct on this?

Upvotes: 0

Views: 2017

Answers (3)

Oleg Butuzov
Oleg Butuzov

Reputation: 5395

  1. interface{} type of empty interface.
  2. you assign []byte or int to any empty variable of empty interface (interface{} type) or you can pass it directly to function that exepts interface values.

Upvotes: 0

blackgreen
blackgreen

Reputation: 44698

interface{}{} is invalid syntax.

It is not an empty interface composite literal — there's no such thing. The following don't compile:

var a interface{}{} = "foo" // not a type
b := interface{}{}          // not a value

From the specs Composite Literals:

Composite literals construct values for structs, arrays, slices, and maps and create a new value each time they are evaluated.

The valid syntax is interface{}, which is the empty interface, i.e. an interface with no name and empty method set.

If you compare it to a named interface, you will see that the extra set of curly braces at the end makes no sense:

type Fooer interface {
    Foo() error
}{} // ???

You can instantiate an empty interface{} by converting nil:

a := (interface{})(nil)

Or you can declare a var of unnamed interface type:

type A struct {}

func (a A) Foo() string {
    return "foo"
}

var a interface{ Foo() string } = A{}

To answer your question:

So, if I wanted to pass a composite type [...]

you can assign any value to a variable of type interface{}, that's about it. Whether the value is composite or not is irrelevant because all types satisfy the empty interface:

var a interface{} = []byte{0x01, 0x02}
var b interface{} = "string_literal"

Playground: https://play.golang.org/p/w-l1dU-6Hb5

Upvotes: 2

draxil
draxil

Reputation: 64

The empty interface interface{} essentially says "I don't care". Anything can be passed as an empty interface. So for your examples they all could be stored as the empty interface.

Possibly a more interesting question is why you want to avoid types in the first place, and what you're trying to achieve. But for the purposes of using interface{} you can pass anything to it, even a "nil".

Upvotes: 0

Related Questions