英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论