args := []interface{}{} 在 golang 中的含义是什么?

huangapple go评论96阅读模式
英文:

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

问题

这段代码看起来可以用作一个可以填充任意类型的列表,但我不理解语法。为什么有两组{}?

args := []interface{}{}

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

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

这段代码中的两组{}用于创建一个空的接口类型切片(slice),即args。接着,使用append函数将check.ID和checkNumber添加到args切片中。最后,args切片被传递给db.Exec函数的可变参数args...,以便作为参数传递给该函数。

英文:

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

答案1

得分: 5

让我们从内部语法到外部语法逐步构建起来。请按照我的描述中的链接,详细了解每个语法元素的解释。

  • interface{} 是一个接口的类型规范,没有方法。通常称为空接口。所有类型都满足空接口。
  • []interface{} 是空接口的slice
  • []interface{}{} 是一个包含空接口元素的slice的复合字面量表达式。

第一组 {} 是接口声明的一部分。接口中没有方法。

第二组 {} 是用于表示该切片的复合字面量表达式。切片中没有元素。

顺便提一下,问题中的代码可以简化为:

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

进一步简化为:

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

编译器会自动从可变参数构建 []interface{}

英文:

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.

huangapple
  • 本文由 发表于 2022年2月15日 05:09:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/71118300.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定