英文:
When `User` is struct, what is `(*User)(nil)`?
问题
这是一个Go语言的代码片段。(*User)(nil)
是一个类型转换表达式,将nil
转换为*User
类型的指针。在这个代码中,v
被声明为*User
类型的指针,并被赋值为nil
。在打印v
的时候,它将输出<nil>
,表示该指针为空指针。
英文:
This compiles:
package main
import (
"fmt"
)
type User struct {
ID int64
}
func main() {
v := (*User)(nil)
fmt.Println(v)
}
Here, what is (*User)(nil)
?
I encountered this notation at go-pg, and had no clue to find an answer because it was very hard to search on google.
答案1
得分: 5
如果User
是一个类型,*User
是另一种类型,即指向User
的指针类型。
(*User)(nil)
是一种类型转换:它将未类型化的nil
预声明标识符转换为(*User)
。你必须将*User
放在括号中,否则表达式将尝试将nil
转换为User
(如果User
是一个结构体,则会在编译时出错),然后对其进行解引用。
因此,v
将是一个类型为*User
的变量,保存着nil
指针值。
v := (*User)(nil)
表达式是一种短变量声明,它等同于以下变量声明的简写形式:
var v *User = nil
当然,这与以下代码是相同的:
var v *User
因为如果初始化表达式缺失,变量将被初始化为其零值,对于所有指针类型来说,零值是nil
。
英文:
If User
is a type, *User
is another type, a pointer type, a pointer to User
.
(*User)(nil)
is a type conversion: it converts the untyped nil
predeclared identifier to (*User)
. You must put *User
into parenthesis, else the expression would try to convert nil
to User
(which is a compile-time error if User
is a struct), and then dereference it.
So v
will be a variable of type *User
, holding the nil
pointer value.
The v := (*User)(nil)
expression is a short variable declaration and it is equivalent (shorthand) to the following variable declaration:
var v *User = nil
Which is of course the same as
var v *User
Because if the initialization expression is missing, the variable will be initialized to its zero value which is nil
for all pointer types.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论