What does args := []interface{}{} mean in golang?


It looks like it can be used as a list that can be filled with any types, but I don’t understand the syntax. Why are there two set of {}?

    args := []interface{}{}

    args = append(args, check.ID, checkNumber)

    err := db.Exec(query, args...).Error


Let’s build this up from the inner syntax to the outer syntax. Follow the links in my description for a detailed explanation of each syntax element.

  • interface{} is a type specification for an interface with no methods. This is commonly called the empty interface. All types satisfy the empty interface.
  • []interface{} is a slice of the empty interface.
  • []interface{}{} is a composite literal expression for a slice of empty interface containing no elements.

The first set of {} is part of the interface declaration. There are no methods in the interface.

The second set of {} is part of the composite literal expression for the slice. There are no elements in the slice.

As a side note, the code in the question can be reduced to:

args := interface{}{check.ID, checkNumber}
err := db.Exec(query, args...).Error

and further to:

err := db.Exec(query, check.ID, checkNumber).Error

The compiler automatically constructs the []interface{} from variadic arguments.

Answered By – Zombo

Answer Checked By – David Marino (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.