user3454396
user3454396

Reputation: 423

What does the double curly brace mean in []interface{}{}

Please note this is double curly braces in this format{}{}, and not nested curly braces {{}}. I am also unsure if this is an empty interface issue, a slice issue or a struct issue. I am guessing it is a combination of at least two of these.

I am learning Golang and I have reached empty interfaces. I see I need to declare a slice of empty interfaces as

[]interface{}{}

or for instance

[]interface{}{"aa","bb"}

I don't just want to blindly start using it. Whereas I understand the idea of empty interfaces, and that an interface contains two portions of data, the value and the type, I just don't understand the {}{} structure? I learned that slices are created with make() or for instance []int{}

What is the extra {} for when using empty interfaces?

Thank you

I have googled it, and went through my tutorials. I also compared it to what I know about structs as I suspect a interface is a struct. My attempts to google golang interfaces yields mainly normal interfaces, with which I have no problem.

Upvotes: 4

Views: 3852

Answers (2)

peterSO
peterSO

Reputation: 166785

interface{} is the empty interface type

[]interface{} is a slice of type empty interface

interface{}{} is an empty interface type composite literal

[]interface{}{} is a slice of type empty interface composite literals


The Go Programming Language Specification

Interface types

Slice types

Composite literals


Take the Go Tour: A Tour of Go

Upvotes: 8

Adrian
Adrian

Reputation: 46552

[]interface{} is the type: a slice [] of empty interface interface{} (which is actually an anonymous inline type declaration). The second set of braces instantiates an instance of that type, so []interface{}{} is an empty slice of empty interface, []interface{}{"aa","bb"} is a slice of empty interface with two items. That could also be []string{"aa","bb"}, a slice of string with two items, which is the same thing with a different type (string in place of interface{}).

You could also have a non-empty interface, like []interface{SomeFunc()}{} being an empty slice of interface{SomeFunc()}, a non-empty anonymous interface type. Or you could do it with an anonymous struct type, like []struct{Foo string}{{"bar"},{"baz"}}. Here there's even more braces - the first pair around the type definition body, the second pair around the slice literal, and within that, one pair each around two struct literals.

Upvotes: 12

Related Questions