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

Time:02-15

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

CodePudding user response:

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.

CodePudding user response:

The := is a shortcut for declaring and initializing the variable in one operation.

The below is a type declaration without initializing the variable.

var args []interface{}

It actually still has a value since every type in go has a default value, like nil, 0 and "", depending on the type. For a slice, it's just a slice of length 0. That's why you also could do the following.

var args []interface{}
args = append(args, check.ID, checkNumber)

To use it, you would then assign some value, to the variable, which corresponds to the type of the variable. In your example, you assign to it the return value of append. Below, I am assigning directly a composite literal.

args = []interface{}{check.ID, checkNumber}

To make life easier, you can do that in one operation. Note the colon before the equal sign :=. It is also a way to let go infer the type of the variable.

args := []interface{}{check.ID, checkNumber}

In your example, it has been initialized but without values inside the slice. So it's a slice of length 0. Mine is a slice of length 2.

To add even more things after initializing, you still need to use append.

  •  Tags:  
  • go
  • Related