Slice of interfaces, what does this syntax mean in go?

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

Slice of interfaces, what does this syntax mean in go?

问题

这是一段接口的代码片段,但为什么变量声明得这么奇怪:( ) ( )。这是什么意思?nil可以用什么代替?

models := []interface{}{
    (*entities.User)(nil),
}

这段代码是在声明一个名为models的切片,其中包含一个接口类型的元素。在这个切片中,使用了一个奇怪的语法(*entities.User)(nil)来声明一个空指针。这里的(*entities.User)表示将entities.User类型转换为指针类型,而(nil)表示空指针。这样的声明可以用来表示一个空的entities.User指针。

在这个代码片段中,nil表示空指针,它可以用来表示一个变量还没有被赋值或者没有有效的数值。在其他情况下,你也可以使用其他值来代替nil,具体取决于你的需求。

英文:

This is a slice of interfaces, but why are variables declared so strange: ( ) ( ). What does it mean? What can be instead of nil?

models := []interface{}{	
	(*entities.User)(nil),
}

答案1

得分: 2

(*T)(v) -- 这是一个类型转换。它将无类型的 nil 转换为有类型的 nil。转换后的 nil 的类型将是 *entities.User

指针类型周围的括号对于编译器来确定你的意图是必要的。如果没有括号,它也可能意味着你试图解引用转换结果,这也是一个有效的表达式,例如 *T(v) 表示将 v 转换为 T 并解引用结果。

规范中更详细地说明了这一点:https://go.dev/ref/spec#Conversions

如果类型以运算符 *<- 开头,或者类型以关键字 func 开头且没有结果列表,在必要时必须使用括号 以避免歧义:

*Point(p)        // 与 *(Point(p)) 相同
(*Point)(p)      // p 被转换为 *Point
<-chan int(c)    // 与 <-(chan int(c)) 相同
(<-chan int)(c)  // c 被转换为 <-chan int
func()(x)        // 函数签名 func() x
(func())(x)      // x 被转换为 func()
(func() int)(x)  // x 被转换为 func() int
func() int(x)    // x 被转换为 func() int(无歧义)
英文:

(*T)(v) -- It's a conversion. It converts the untyped nil to a typed nil. The type of the nil after the conversion will be *entities.User.

The parentheses around the pointer type are necessary for the compiler to know what you mean to do. Without the parentheses it could as well mean that you are trying to dereference the result of the conversion, which is also a valid expression, e.g. *T(v) means convert v to T and dereference the result.

The spec lays it out in more detail: https://go.dev/ref/spec#Conversions

> If the type starts with the operator * or &lt;-, or if the type starts with the keyword func and has no result list, it must be parenthesized when necessary to avoid ambiguity:
>
> none
&gt; *Point(p) // same as *(Point(p))
&gt; (*Point)(p) // p is converted to *Point
&gt; &lt;-chan int(c) // same as &lt;-(chan int(c))
&gt; (&lt;-chan int)(c) // c is converted to &lt;-chan int
&gt; func()(x) // function signature func() x
&gt; (func())(x) // x is converted to func()
&gt; (func() int)(x) // x is converted to func() int
&gt; func() int(x) // x is converted to func() int (unambiguous)
&gt;

huangapple
  • 本文由 发表于 2022年4月16日 17:16:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/71892623.html
匿名

发表评论

匿名网友

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

确定